How can I delete a query string parameter in JavaScript?

Viewed 289399

Is there better way to delete a parameter from a query string in a URL string in standard JavaScript other than by using a regular expression?

Here's what I've come up with so far which seems to work in my tests, but I don't like to reinvent querystring parsing!

function RemoveParameterFromUrl( url, parameter ) {

    if( typeof parameter == "undefined" || parameter == null || parameter == "" ) throw new Error( "parameter is required" );

    url = url.replace( new RegExp( "\\b" + parameter + "=[^&;]+[&;]?", "gi" ), "" ); "$1" );

    // remove any leftover crud
    url = url.replace( /[&;]$/, "" );

    return url;
}
27 Answers

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.

Copied from bobince answer, but made it support question marks in the query string, eg

http://www.google.com/search?q=test???+something&aq=f

Is it valid to have more than one question mark in a URL?

function removeUrlParameter(url, parameter) {
  var urlParts = url.split('?');

  if (urlParts.length >= 2) {
    // Get first part, and remove from array
    var urlBase = urlParts.shift();

    // Join it back up
    var queryString = urlParts.join('?');

    var prefix = encodeURIComponent(parameter) + '=';
    var parts = queryString.split(/[&;]/g);

    // Reverse iteration as may be destructive
    for (var i = parts.length; i-- > 0; ) {
      // Idiom for string.startsWith
      if (parts[i].lastIndexOf(prefix, 0) !== -1) {
        parts.splice(i, 1);
      }
    }

    url = urlBase + '?' + parts.join('&');
  }

  return url;
}

If it's an instance of URL, use the delete function of searchParams

let url = new URL(location.href);
url.searchParams.delete('page');

This is a clean version remove query parameter with the URL class for today browsers:

function removeUrlParameter(url, paramKey)
{
  var r = new URL(url);
  r.searchParams.delete(paramKey);
  return r.href;
}

URLSearchParams not supported on old browsers

https://caniuse.com/#feat=urlsearchparams

IE, Edge (below 17) and Safari (below 10.3) do not support URLSearchParams inside URL class.

Polyfills

URLSearchParams only polyfill

https://github.com/WebReflection/url-search-params

Complete Polyfill URL and URLSearchParams to match last WHATWG specifications

https://github.com/lifaon74/url-polyfill

Here a solution that:

  1. uses URLSearchParams (no difficult to understand regex)
  2. updates the URL in the search bar without reload
  3. maintains all other parts of the URL (e.g. hash)
  4. removes superflous ? in query string if the last parameter was removed
function removeParam(paramName) {
    let searchParams = new URLSearchParams(window.location.search);
    searchParams.delete(paramName);
    if (history.replaceState) {
        let searchString = searchParams.toString().length > 0 ? '?' + searchParams.toString() : '';
        let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname +  searchString + window.location.hash;
        history.replaceState(null, '', newUrl);
    }
}

Note: as pointed out in other answers URLSearchParams is not supported in IE, so use a polyfill.

The above version as a function

function removeURLParam(url, param)
{
 var urlparts= url.split('?');
 if (urlparts.length>=2)
 {
  var prefix= encodeURIComponent(param)+'=';
  var pars= urlparts[1].split(/[&;]/g);
  for (var i=pars.length; i-- > 0;)
   if (pars[i].indexOf(prefix, 0)==0)
    pars.splice(i, 1);
  if (pars.length > 0)
   return urlparts[0]+'?'+pars.join('&');
  else
   return urlparts[0];
 }
 else
  return url;
}

I practically wrote the following function to process the url parameters and get the final status as a string and redirect the page. Hopefully it benefits.

function addRemoveUrlQuery(addParam = {}, removeParam = [], startQueryChar = '?'){

    let urlParams = new URLSearchParams(window.location.search);

    //Add param
    for(let i in addParam){
        if(urlParams.has(i)){ urlParams.set(i, addParam[i]); }
        else                { urlParams.append(i, addParam[i]); }
    }

    //Remove param
    for(let i of removeParam){
        if(urlParams.has(i)){
            urlParams.delete(i);
        }
    }

    if(urlParams.toString()){
        return startQueryChar + urlParams.toString();
    }

    return '';
}

For example, when I click a button, I want the page value to be deleted and the category value to be added.

let button = document.getElementById('changeCategory');
button.addEventListener('click', function (e) {

    window.location = addRemoveUrlQuery({'category':'cars'}, ['page']);

});

I think it was very useful!

another direct & simpler answer would be

let url = new URLSearchParams(location.search)
let key = 'some_key'

return url.has(key)
    ? location.href.replace(new RegExp(`[?&]${key}=${url.get(key)}`), '')
    : location.href

If you have a polyfill for URLSearchParams or simply don't have to support Internet Explorer, that's what I would use like suggested in other answers here. If you don't want to depend on URLSearchParams, that's how I would do it:

function removeParameterFromUrl(url, parameter) {
  const replacer = (m, p1, p2) => (p1 === '?' && p2 === '&' ? '?' : p2 || '')
  return url.replace(new RegExp(`([?&])${parameter}=[^&#]+([&#])?`), replacer)
}

It will replace a parameter preceded by ? (p1) and followed by & (p2) with ? to make sure the list of parameters still starts with a question mark, otherwise, it will replace it with the next separator (p2): could be &, or #, or undefined which falls back to an empty string.

const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())

Glad you scrolled here.

I would suggest you to resolve this task by next possible solutions:

  1. You need to support only modern browsers (Edge >= 17) - use URLSearchParams.delete() API. It is native and obviously is the most convenient way of solving this task.
  2. If this is not an option, you may want to write a function to do this. Such a function does
    • do not change URL if a parameter is not present
    • remove URL parameter without a value, like http://google.com/?myparm
    • remove URL parameter with a value, like http://google.com/?myparm=1
    • remove URL parameter if is it in URL twice, like http://google.com?qp=1&qpqp=2&qp=1
    • Does not use for loop and not modify array during looping over it
    • is more functional
    • is more readable than regexp solutions
    • Before using make sure your URL is not encoded

Works in IE > 9 (ES5 version)

function removeParamFromUrl(url, param) {  // url: string, param: string
  var urlParts = url.split('?'),
      preservedQueryParams = '';

  if (urlParts.length === 2) {
    preservedQueryParams = urlParts[1]
      .split('&')
      .filter(function(queryParam) {
        return !(queryParam === param || queryParam.indexOf(param + '=') === 0)
      })
      .join('&');
  }

  return urlParts[0] +  (preservedQueryParams && '?' + preservedQueryParams); 
}

Fancy ES6 version

function removeParamFromUrlEs6(url, param) {
  const [path, queryParams] = url.split('?');
 let preservedQueryParams = '';

  if (queryParams) {
    preservedQueryParams = queryParams
      .split('&')
      .filter(queryParam => !(queryParam === param || queryParam.startsWith(`${param}=`)))
      .join('&');
  }

  return `${path}${preservedQueryParams && `?${preservedQueryParams}`}`;  
}

See how it works here

function removeParamInAddressBar(parameter) {
    var url = document.location.href;
    var urlparts = url.split('?');

    if (urlparts.length >= 2) {
        var urlBase = urlparts.shift();
        var queryString = urlparts.join("?");

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = queryString.split(/[&;]/g);
        for (var i = pars.length; i-- > 0;) {
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }

        if (pars.length == 0) {
            url = urlBase;
        } else {
            url = urlBase + '?' + pars.join('&');
        }

        window.history.pushState('', document.title, url); // push the new url in address bar
    }
    return url;
}
Related