Delete part of query string from url without page reload

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Admin
Site Admin
Posts: 805

Delete part of query string from url without page reload

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=...').

Similar Topics