Skip to main content

Javascript add/update parameter to url string

One of the best code I saw is the below code which is a good way to change the URL without refresh the page, here is the code

 

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
//You can reload the url like so
 var newUrl=updateQueryStringParameter(window.location.href,"some_param","replaceValue");
 window.history.pushState("", "Page Title Here", newUrl);

 

Reference : 

javascript add parameter to url string Code Example (codegrepper.com)