add get parameter to url javascript code example
Example 1: js add params to url
function setQueryStringParameter(name, value) {
const params = new URLSearchParams(window.location.search);
params.set(name, value);
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}
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);