193

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;
}
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130

31 Answers31

202
"[&;]?" + 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;
}
gagikm
  • 38
  • 5
bobince
  • 528,062
  • 107
  • 651
  • 834
  • Good point about the bar matching the foobar. I've updated my original regex to require a ? or a [&;] at the start. Also reading over your solution to consider it... – Matthew Lock Oct 28 '09 at 03:06
  • and added "g" to make the replacement global ;) – Matthew Lock Oct 28 '09 at 03:12
  • 5
    If you want to get rid of the "?" when there are no parameters after the removal, add an if condition to test if pars.length==0, and if it is 0, then make "url = urlparts[0]" instead of appending the "?". – johnmcaliley Nov 14 '10 at 18:42
  • @Matthew: Actually a regexp passed to `split` always splits globally, you don't have to explicitly set `g`. Shame really, as a single-split feature would have been useful. (`split(..., 1)` does something useless instead.) – bobince Nov 15 '10 at 11:41
  • I didn't see that for loop before... why do you make the comments with ampersand?, Is it CoffeeScript??? I don't think this is pure JS – Jaider Apr 23 '12 at 17:14
  • 2
    Is it safe to compare the URL fragment with encodeURIComponent(parameter)? What if the URL encodes the parameter name differently? For example 'two%20words' versus 'two+words'. To deal with this, it might be better to decode the parameter name and compare it as a normal string. – Adrian Pronk Mar 18 '13 at 20:50
  • 10
    Mild improvement, so that when the final URL Parameter is removed, the '?' gets removed too: Change the line `url= urlparts[0]+'?'+pars.join('&');` to `url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");` – Cody S Sep 24 '15 at 17:23
  • @CodyS As I have tested the code, it does not remove "?"!! To remove it, follow the third comment. – Aboozar Rajabi Apr 17 '16 at 09:22
  • @AboozarRajabi I strongly doubt it. Just read the code. It's not exactly complicated (I mean, there's a ternary operator, so it isn't overly simple either, but still)...in fact, I'd go so far as to say it's obvious the '?' will only be included if there are URL parameters on the URL (if pars.length > 0). I've got 5 upvotes backing my answer too, FWIW. – Cody S Apr 18 '16 at 23:29
  • strange no one complaining about case insensitive. change `pars[i].lastIndexOf(prefix, 0)` become `pars[i].toLowerCase().lastIndexOf(prefix.toLowerCase(), 0)` – ktutnik May 24 '16 at 07:59
  • Also doesn't remove parameters which are listed as arrays. – Keir Simmons Jan 20 '17 at 01:56
  • @KeirSimmons: ? If you mean parameters with `[]` at the end of the name then just include `[]` at the end of the name. JavaScript and the web in general doesn't know anything special about parameters with `[]` at the end, it's only PHP which uses that as a (broken) is-array flag. – bobince Jan 24 '17 at 22:34
  • 2
    @ktutnik/@JonasAxelsson URL query parameters are not naturally case-insensitive. – bobince Nov 21 '17 at 22:19
94

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`)
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • 2
    Note that `URLSearchParams` is not supported by IE, Edge 16 and iOS 10.2 Safari. (ref: https://caniuse.com/#feat=urlsearchparams) – khiav reoy Apr 02 '18 at 17:09
  • 9
    @khiavreoy Yeah. Like the first two words in the answer give the same link :) – Yury Tarabanko Apr 02 '18 at 17:40
  • Update 2022-01-06: `URLSearchParams` now works in all browsers except IE, Opera Mini, and Baidu. – therealrodk Jan 06 '22 at 21:58
  • 2
    And if you're working from a full URL instead of a string with just the parameters you can use `searchParams.delete` of the `URL` constructor. See this answer: https://stackoverflow.com/a/62022690/1913230 – Harm Jan 28 '22 at 06:45
64

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.

santillanix
  • 1,947
  • 18
  • 17
  • 4
    what if only one single search param needs deletion without changing other search params? thanks! – xjlin0 Jul 03 '21 at 14:44
  • This doesn't work well on SPA, I'm using Vue (with Vue Router) and it also removes the router path – Arthur Borba Nov 30 '22 at 21:31
  • @ArthurBorba Vue Router has a method called "replace" that will help you with that. https://router.vuejs.org/guide/essentials/navigation.html – James Totty Mar 07 '23 at 22:25
36

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

let url = new URL(location.href);
url.searchParams.delete('page');
Wariored
  • 1,303
  • 14
  • 25
28

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.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Jared
  • 51
  • 3
  • 4
  • 1
    Here is an improved regex that works when the paramater has no value (i.e. 'ex.com?removeMe'), and will not replace the parameter in fragments (i.e. 'ex.com?#&dont=removeMe') or paths (i.e. 'ex.com/&dont=removeMe'): `url.replace(new RegExp('^([^#]*\?)(([^#]*)&)?' + parameter + '(\=[^]*)?(&|#|$)' ), '$1$3$5').replace(/^([^#]*)((\?)&|\?(#|$))/,'$1$3$4')` – Stephen M. Harris Sep 03 '15 at 16:19
  • This won't work Stephen M. Harris. Try to give your code an empty String as a param and see what happens... – David Fischer Feb 25 '18 at 15:48
23

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;
}
Community
  • 1
  • 1
LukePH
  • 404
  • 5
  • 11
  • 2
    I believe the `???` is invalid syntax and should never occur in a URL`. –  Sep 23 '16 at 18:30
  • @torazaburo Have a look at the stackoverflow question I posted: "Is it valid to have more than one question mark in a URL?", the answer appears to be yes. Also this was years ago so I cannot remember the details but I ran into problems when this wasn't correctly handled. – LukePH Sep 24 '16 at 08:30
  • I'm not saying they do not exist in the real world, and one would probably want to be able to handle them, but in a properly formed URL, the question mark is a "reserved character" and any question mark other than the one introducing the query parameters should be URL-encoded. –  Sep 24 '16 at 09:23
  • 1
    You may want to replace the last line with `return url.endsWith("?") ? url.slice(0,-1) : url;` to cover the case where the parameter to be removed is the only one in the query string – Konamiman Nov 25 '16 at 11:33
  • @Konamiman That would change parameter data when for example removing 'aq' from: http://www.google.com/search?q=test???&aq=f but I get what you mean, it would be nice to clean up the url even if the ? doesn't do any harm. The logic just need to make sure the last ? is also the first ?. – LukePH Nov 25 '16 at 14:29
17

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.

klues
  • 847
  • 12
  • 21
16

Here is what I'm using:

if (location.href.includes('?')) { 
    history.pushState({}, null, location.href.split('?')[0]); 
}

Original URL: http://www.example.com/test/hello?id=123&foo=bar
Destination URL: http://www.example.com/test/hello

Now this answer seems even better! (not fully tested though)

Basj
  • 41,386
  • 99
  • 383
  • 673
14

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

Heroselohim
  • 1,241
  • 1
  • 18
  • 23
12

Anyone interested in a regex solution I have put together this function to add/remove/update a querystring parameter. Not supplying a value will remove the parameter, supplying one will add/update the paramter. If no URL is supplied, it will be grabbed from window.location. This solution also takes the url's anchor into consideration.

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}

UPDATE

There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.

UPDATE 2

@schellmax update to fix situation where hashtag symbol is lost when removing a querystring variable directly before a hashtag

ellemayo
  • 3,258
  • 2
  • 20
  • 30
  • 1
    This doesn't work if you have two query strings and remove the first. The passed in url becomes invalid because the ? is removed when it should be preserved. – Blake Niemyjski Mar 06 '13 at 15:07
  • 1
    @BlakeNiemyjski thanks for finding that bug, I have updated the script to include a workaround for the first parameter – ellemayo Mar 07 '13 at 15:34
  • 1
    will accidentally remove the hash here: `UpdateQueryString('a', null, 'http://www.test.com?a=b#c');` – schellmax Sep 13 '13 at 16:07
  • Cool function, thanks. FYI: while using this with an ignore array keys in each()` loops, you may need to define an ever shrinking `url` for each replacement iteration. But, that means you must enter a `value` in the arguments, which will leave the querystring half removed. To counter this, use `undefined` or `null` for `value` argument like: `url_from_last_iteration = UpdateQueryString(current_ignore_key, undefined/null, url_from_last_iteration);` – dhaupin Jun 28 '17 at 15:56
8

Assuming you want to remove key=val parameter from URI:

function removeParam(uri) {
   return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}
ssh_imov
  • 1
  • 1
  • 2
  • Works well but escaping the first question mark in the regex is unnecessary and can cause linter error: `/([&?]key=val*$|key=val&|[?&]key=val(?=#))/` may be preferable when using a linter like eslint – quetzaluz Jul 17 '18 at 20:59
6

Heres a complete function for adding and removing parameters based on this question and this github gist: https://gist.github.com/excalq/2961415

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {

        updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty

            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it

            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string

            params = urlQueryString + '&' + newParam;

        }

    }
    window.history.replaceState({}, "", baseUrl + params);
};

You can add parameters like this:

updateQueryStringParam( 'myparam', 'true' );

And remove it like this:

updateQueryStringParam( 'myparam', null );

In this thread many said that the regex is probably not the best/stable solution ... so im not 100% sure if this thing has some flaws but as far as i tested it it works pretty fine.

GDY
  • 2,872
  • 1
  • 24
  • 44
4

Using jQuery:

function removeParam(key) {
    var url = document.location.href;
    var params = url.split('?');
    if (params.length == 1) return;

    url = params[0] + '?';
    params = params[1];
    params = params.split('&');

    $.each(params, function (index, value) {
        var v = value.split('=');
        if (v[0] != key) url += value + '&';
    });

    url = url.replace(/&$/, '');
    url = url.replace(/\?$/, '');

    document.location.href = url;
}
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
3

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;
}
Graham
  • 1
  • 1
2

All of the responses on this thread have a flaw in that they do not preserve anchor/fragment parts of URLs.

So if your URL looks like:

http://dns-entry/path?parameter=value#fragment-text

and you replace 'parameter'

you will lose your fragment text.

The following is adaption of previous answers (bobince via LukePH) that addresses this problem:

function removeParameter(url, parameter)
{
  var fragment = url.split('#');
  var urlparts= fragment[0].split('?');

  if (urlparts.length>=2)
  {
    var urlBase=urlparts.shift(); //get first part, and remove from array
    var queryString=urlparts.join("?"); //join it back up

    var prefix = encodeURIComponent(parameter)+'=';
    var pars = queryString.split(/[&;]/g);
    for (var i= pars.length; i-->0;) {               //reverse iteration as may be destructive
      if (pars[i].lastIndexOf(prefix, 0)!==-1) {   //idiom for string.startsWith
        pars.splice(i, 1);
      }
    }
    url = urlBase + (pars.length > 0 ? '?' + pars.join('&') : '');
    if (fragment[1]) {
      url += "#" + fragment[1];
    }
  }
  return url;
}
Will Lanni
  • 923
  • 12
  • 25
Bret Weinraub
  • 1,943
  • 15
  • 21
  • 1
    Mild improvement, so that when the final URL Parameter is removed, the '?' gets removed too: Change the line `url = urlBase+'?'+pars.join('&');` to `url = urlBase + (pars.length > 0 ? '?' + pars.join('&') : "");` – Cody S Sep 24 '15 at 17:36
  • 1
    what if # comes first ? http://dns-entry/path#fragment-text?parameter=value – ajayv Feb 04 '19 at 09:32
2

You should be using a library to do URI manipulation as it is more complicated than it seems on the surface to do it yourself. Take a look at: http://medialize.github.io/URI.js/

Ryan
  • 7,499
  • 9
  • 52
  • 61
2

From what I can see, none of the above can handle normal parameters and array parameters. Here's one that does.

function removeURLParameter(param, url) {
    url = decodeURI(url).split("?");
    path = url.length == 1 ? "" : url[1];
    path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
    path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
    path = path.replace(/^&/, "");
    return url[0] + (path.length
        ? "?" + path
        : "");
}

function addURLParameter(param, val, url) {
    if(typeof val === "object") {
        // recursively add in array structure
        if(val.length) {
            return addURLParameter(
                param + "[]",
                val.splice(-1, 1)[0],
                addURLParameter(param, val, url)
            )
        } else {
            return url;
        }
    } else {
        url = decodeURI(url).split("?");
        path = url.length == 1 ? "" : url[1];
        path += path.length
            ? "&"
            : "";
        path += decodeURI(param + "=" + val);
        return url[0] + "?" + path;
    }
}

How to use it:

url = location.href;
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

url = removeURLParameter("sold", url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = removeURLParameter("tags", url)
    -> http://example.com/

url = addURLParameter("tags", ["single", "promo"], url)
    -> http://example.com/?tags[]=single&tags[]=promo

url = addURLParameter("sold", 1, url)
    -> http://example.com/?tags[]=single&tags[]=promo&sold=1

Of course, to update a parameter, just remove then add. Feel free to make a dummy function for it.

Keir Simmons
  • 1,634
  • 7
  • 21
  • 37
  • `path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");` I would change the regex to `[\\w]*` to include parameters like "param=" without values. – Tomás May 29 '17 at 09:02
1

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!

Emrah Tuncel
  • 678
  • 8
  • 13
1

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
ctf0
  • 6,991
  • 5
  • 37
  • 46
1

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

Shevchenko Viktor
  • 5,206
  • 2
  • 17
  • 26
1

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.

pmrotule
  • 9,065
  • 4
  • 50
  • 58
1

Here's a simple non-regex way to get rid of all query params:

const url = "https://example.com";
const urlObj = new URL(url);
const urlWithoutQueryParams = `${urlObj.origin}${urlObj.pathname}`;
0

A modified version of solution by ssh_imov

function removeParam(uri, keyValue) {
      var re = new RegExp("([&\?]"+ keyValue + "*$|" + keyValue + "&|[?&]" + keyValue + "(?=#))", "i"); 
      return uri.replace(re, '');
    }

Call like this

removeParam("http://google.com?q=123&q1=234&q2=567", "q1=234");
// returns http://google.com?q=123&q2=567
kiranvj
  • 32,342
  • 7
  • 71
  • 76
0

This returns the URL w/o ANY GET Parameters:

var href = document.location.href;
var search = document.location.search;
var pos = href.indexOf( search );
if ( pos !== -1 ){
    href = href.slice( 0, pos );
    console.log( href );
}
0
const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())
Neeraj Pathak
  • 311
  • 2
  • 18
  • This is an answer to a question that is very old and already has an accepted answer. Please explain what this answer has to offer which is new/different from the other answers. Also, answers should include explanations and not just code. – nurdyguy Oct 29 '19 at 21:11
0
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;
}
Alex
  • 8,908
  • 28
  • 103
  • 157
0
function clearQueryParams() {
  const paramName = 'abc';
  const url = new URL(window.location.href);
  url.searchParams.delete(paramName);
  const newUrl = url.search ? url.href : url.href.replace('?', '');
  window.history.replaceState({}, document.title, newUrl); //if you don't want to reload
  window.location = newUrl; //if you want to reload
}
Abdur Rafay
  • 73
  • 1
  • 6
0
const removeQueryParams = (url: string) => {
   const urlParts = url.split("?");
   return urlParts[0];
};
Ilir Hushi
  • 99
  • 5
0

Here is a better a way to remove any query param from url and update the URL (if needed)

const myUrl = 'https://example.com?val=3&temp=20'
const newUrl = new URL(myUrl);

// delete any param (lets say 'temp' in our case)
newUrl.searchParams.delete('temp');
console.log(newUrl.href); // https://example.com/?val=3

//set any param (lets say 'newParam' in our case)
newUrl.searchParams.set('newParam', 20);
console.log(newUrl.href) // // https://example.com/?val=3&newParam=20

If you want to set the updated URL with no page reload, then use the History API as:

history.replaceState({}, null, newUrl.href);
Jayant Sharma
  • 87
  • 1
  • 7
-2

If you're into jQuery, there is a good query string manipulation plugin:

Asaph
  • 159,146
  • 25
  • 197
  • 199
Damovisa
  • 19,213
  • 14
  • 66
  • 88
-2
function removeQueryStringParameter(uri, key, value) 
{

var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");

    var separator = uri.indexOf('?') !== -1 ? "&" : "?";

    if (uri.match(re)) {

        return uri.replace(re, '');

    }
}
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47