Page 1 of 1

Delete part of query string from url without page reload

Posted: 20 Oct 2018, 14:47
by Admin
The delPartUrl() function from the following JavaScript code can be used to delete part of query string from page url in browser, without affecting or reloading the page.

Code: Select all

<script>
//delete part of query string from url without affecting the page
//from: https://coursesweb.net/
//receives a string with name of the part in query
function delPartUrl(p){
  var pg_url = window.location.toString();
  var rgx = new RegExp('[&]{0,1}'+p+'=[^&]+', 'i');
  let is_p = pg_url.match(rgx);

  //if p in url
  if(is_p){
    pg_url = pg_url.replace(is_p[0], '');
    history.replaceState(null, '', pg_url);
  }
}

//test, delete 'sid=...' from page address in browser
delPartUrl('sid');
</script>
- In the example above, if the initial address of the page is:
//localhost/index.php?ir=12&sid=78sdy&nm=2h
in browser it will show:
//localhost/index.php?ir=12&nm=2 (without 'sid=...').