'Removing URL parameters with Javascript - my solution works, except in some fringe cases and I'm unsure how to fix?

In a nutshell, I have some Javascript I use to remove parameters from the URL. It looks like:

//Define variable
var objQueryString={};

//Get querystring value
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, " "));
}

//Function used to remove querystring
function removeQString(key) {
    
    // ignore this bit, I was just playing around with looping multiple times
    for(i=0; i<5; i++) {
        
    var urlValue=document.location.href;
    
    //Get query string value
    var searchUrl=location.search;
    
    if(key!="") {
        oldValue = getParameterByName(key);
        removeVal=key+"="+oldValue;
        if(searchUrl.indexOf('?'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('?'+removeVal+'&','?');
        }
        else if(searchUrl.indexOf('&'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('&'+removeVal+'&','&');
        }
        else if(searchUrl.indexOf('?'+removeVal)!= "-1") {
            urlValue=urlValue.replace('?'+removeVal,'');
        }
        else if(searchUrl.indexOf('&'+removeVal)!= "-1") {
            urlValue=urlValue.replace('&'+removeVal,'');
        }
    }
    else {
        var searchUrl=location.search;
        urlValue=urlValue.replace(searchUrl,'');
    }
    history.pushState({state:1, rand: Math.random()}, '', urlValue);
}
location.reload(); 
}

I can trigger it using something like:

<a href="#" onClick="removeQString('budget')">

This works absolutely fine, except when a URL parameter carries certain encoding. Eg, a date/time variable might look like:

?expdate=2022-02-13T11%3A25

In the above case, the script can't identify and remove and I am unsure how to fix? Can anyone point me in the right direction?



Solution 1:[1]

As someone suggested, I have moved away from this rather clunky solution to simply using URLSearchParams. I'd avoided this for IE compatability, but it's too much of a pain to retain.

Using the following now instead:

function removeParam(key) {
    let url = new URL(window.location.href);
    let params = new URLSearchParams(url.search);

    params.delete(key);
    newURL = location.protocol + '//' + location.host + location.pathname + '?' + params;
    window.location.replace(newURL);
}

Solution 2:[2]

Your whole approach seems to be a bit overcomplicated to me. Why not just split the search string by & and then filter out the value that starts with the specific key?

function removeKey(key, querystring) {
  if (querystring.length <= 1) return ""; //or whatever to do if no parameters are present
  querystring = querystring.substring(1); //remove the initial '?'  
  var 
    queryarray = querystring.split("&"); //split into parameters
  if (key) {
    queryarray = queryarray.filter(function(x) { 
      //remove all elements which start with "key="
      return x.indexOf(key+"=") != 0;
    });
  }
  else {
     //do whatever necessary if no key is given 
  }
  
  //join the query back together  (or return an empty string if no parameters left
  return queryarray.length
    ? "?" + queryarray.join("&")
    : "";
}

console.log("1", removeKey("q1", "?q1=abc&q2=xyz&q3=123&q4=blubb%234%xyz"))
console.log("2", removeKey("q1", "?q1=abc"))
console.log("3", removeKey("q1", "?"))
console.log("4", removeKey("q1", ""))

Solution 3:[3]

You do unnecessary work here. You already capturing some data with regexp, just finish the job with it. It is still naive and will fail on data deliberately encoded to avoid it, but otherwise works with same limitations as your initial key parser - in fact I just copypasted most of code from you.

function removeQString(query, key) {
    key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("([?&])" + key + "=([^&#]*)")
    return query.replace(regex, '').replace(/^&/, '?')
}

console.log(removeQString('?expdate=2022-02-13T11%3A25&whatever=123', 'expdate'))
// ?whatever=123
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'q'))
// ?oq=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'oq'))
// ?q=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'ie'))
// ?q=url+query+examples&oq=url+query+examples&sourceid=chrome

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Damo
Solution 2 derpirscher
Solution 3 Oleg V. Volkov