Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a query string parameter in JavaScript?

People also ask

How do I remove a query param?

Use the useSearchParams hook to get the current location's search params. Use the delete() method to delete each query param, e.g. searchParams. delete('q') .

How do I remove a question mark from a query string?

Remove a Querystring from a URL in JavaScript # To remove a querystring from a url, use the split() method to split the string on a question mark and access the array element at index 0 , e.g. url. split('? ')[0] .

How do I clear URLSearchParams?

delete() The delete() method of the URLSearchParams interface deletes the given search parameter and all its associated values, from the list of all search parameters.

What is URLSearchParams?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


"[&;]?" + 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&param2=2&param3=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.


I don't see major issues with a regex solution. But, don't forget to preserve the fragment identifier (text after the #).

Here's my solution:

function RemoveParameterFromUrl(url, parameter) {
  return url
    .replace(new RegExp('[?&]' + parameter + '=[^&#]*(#.*)?$'), '$1')
    .replace(new RegExp('([?&])' + parameter + '=[^&]*&'), '$1');
}

And to bobince's point, yes - you'd need to escape . characters in parameter names.