How can I delete a query string parameter in JavaScript?
"[&;]?" + parameter + "=[^&;]+"
Seems dangerous because it parameter βbarβ would match:
?a=b&foobar=c
Also, it would fail if parameter
contained any characters that are special in RegExp, such as β.β. And it's not a global regex, so it would only remove one instance of the parameter.
I wouldn't use a simple RegExp for this, I'd parse the parameters in and lose the ones you don't want.
function removeURLParameter(url, parameter) { //prefer to use l.search if you have a location/link object var urlparts = url.split('?'); if (urlparts.length >= 2) { var prefix = encodeURIComponent(parameter) + '='; var pars = urlparts[1].split(/[&;]/g); //reverse iteration as may be destructive for (var i = pars.length; i-- > 0;) { //idiom for string.startsWith if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : ''); } return url;}
Modern browsers provide URLSearchParams
interface to work with search params. Which has delete
method that removes param by name.
if (typeof URLSearchParams !== 'undefined') { const params = new URLSearchParams('param1=1¶m2=2¶m3=3') console.log(params.toString()) params.delete('param2') console.log(params.toString())} else { console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)}
You can change the URL with:
window.history.pushState({}, document.title, window.location.pathname);
this way, you can overwrite the URL without the search parameter, I use it to clean the URL after take the GET parameters.