I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL
This function might be helpful
function updateUrlParameter(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).
function setQueryStringParameter(name, value) {
const params = new URLSearchParams(window.location.search);
params.set(name, value);
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}
I think what you need is remove window.location.href
and leave '?' +
.
var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);