3

I am trying to create a function to remove a particular querystring and its value from the url .

For eg: if i have a url like

var url = www.foo.com/test?name=kevin&gender=Male&id=1234

If i pass name -> it should remove the key and value for name. the url should become

www.foo.com/test?gender=Male&id=1234

i have a Function ReturnRefinedURL(key,url)

and i am doing this in the Function

function ReturnRefinedURL(key,url)
{
var Value  = getParameterByName(key); // This returns kevin
var stringToBeRemoved = 'key +'='+ Value+'&'; // string becomes 'name=kevin&'
return url.replace(stringToBeRemoved, '');
}

//Found this in Google:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

So when i call the method ReturnRefinedURL('name',window.location.href);

This works!!! But looking for a more elegant and fool proof method.
* This wont work if name parameter is the second one in the query string. (the '&' will still be retained)

Night Monger
  • 770
  • 1
  • 10
  • 33

3 Answers3

18

Little bit of more search and then you can end up here:

 var url = "www.foo.com/test?name=kevin&gender=Male&id=1234";
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);
            }
        }

        url= urlparts[0]+'?'+pars.join('&');
        return url;
    } else {
        return url;
    }
}

console.log(removeURLParameter(url, 'name'));
console.log(removeURLParameter(url, 'gender'));

Jsfiddle example

Community
  • 1
  • 1
SSA
  • 5,433
  • 4
  • 36
  • 50
  • Thanks a lot.. Wonder how i missed the link. I did Search!! :( – Night Monger Oct 08 '14 at 19:15
  • Can you please provide a solution which can add parameter to the click event and also remove parameter on that click event i.e I want to add new parameter or change value of existing parameter and remove one of the existing parameter on a single click – Hetal1311 Aug 13 '17 at 17:38
  • Can update for case sensitive issue? – Yiping Oct 26 '17 at 07:08
2

You can simply do this

function returnRefinedURL(key, url){
   return url.replace(new RegExp(key + "=\\w+"),"").replace("?&","?")
  .replace("&&","&"); 
}

Tested all the use-cases and the above works perfectly.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • i tried your method..it works fine when i pass industry.. but when i pass category.. it breaks.. can you tell me what is wrong? the url i tried : `'http://foo.com/en-gb/search-results?k=&l=&a=1&b=5&industry=technology%7c&jobCategories=ba%7cba%5cCOMMERCIAL%7cba%5cCORPORATE%7c' – Night Monger Oct 08 '14 at 18:43
  • @NightMonger I had the same case as yours in that my query string parameters were encoded. @AmitJoki 's approach still works with some regex updates: `return url.replace(new RegExp(key + "[\\s\\S\\d]+?((?=$)|(?=&))"), "").replace("?&", "?").replace("&&", "&").replace(new RegExp("\\?$"), "");` – buzz Jul 02 '21 at 19:20
0

I'd suggest:

// obviously in real use, you could just access 'document.location'
// within the function:
function returnRefinedURL (key, url) {
    // separating the key-value ('search') portion of the URL from the rest:
    var urlParts = url.split('?');
    // if we have only a single array-element, or if the key to remove
    // is not found in the URL, we quit here and return the same unchanged URL:
    if (urlParts.length === 1 || url.indexOf(key) === -1 ) {
        // there were no parameters, or the
        // key wasn't present
        return url;
    }
    else {
        // otherwise, we split the key-value string on the '&' characters,
        // for an array of key=value strings:
        var keyValues = urlParts[1].split('&'),
        // filtering that array:
            refinedKeyValues = keyValues.filter(function (keyValuePair) {
                // keeping only those array elements that don't /start with/
                // the key to be removed:
                return keyValuePair.indexOf(key) !== 0;
            // joining the key=value pairs back into a string:
            }).join('&');
    }
    // returning the refined URL:
    return urlParts[0] + '?' + refinedKeyValues;
}

// beyond this point is entirely irrelevant, it's just for visual feedback:
document.getElementById('output').textContent = returnRefinedURL('name', 'www.foo.com/test?name=kevin&gender=Male&id=1234');
#output::before {
  content: 'output: ';
}
<div id="output"></div>

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410