update parameters in URL with history.pushState()
I think what you need is remove window.location.href
and leave '?' +
.
var pageUrl = '?' + queryString;window.history.pushState('', '', pageUrl);
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}`));}
Hi in order to keep the last part of the url and just play with parameters, you can create a new URL object like so:
// e.g url: sample.com/testpage/testvar url = new URL(window.location);url.searchParams.set('foo', 'bar');window.history.pushState({}, '', url);// outcome: sample.com/testpage/test?foo=bar// you can remove, just the param part, like so:url.searchParams.delete('foo');