javascript update query string code example
Example 1: js update query string
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("foo", "bar");
window.location.search = searchParams.toString();
Example 2: javascript set query parameter
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;
}
}
var newUrl=updateQueryStringParameter(window.location.href,"some_param","replaceValue");
window.history.pushState("", "Page Title Here", newUrl);