How to remove query string parameters in JavaScript?
P粉239164234
P粉239164234 2023-08-20 18:46:10
0
2
527
<p>Is there a better way to remove parameters from a URL string's query string than standard JavaScript using regular expressions? </p> <p>This is what I've come up with so far, and it seems to work in my tests, but I don't like reinventing query string parsing! </p> <pre class="brush:php;toolbar:false;">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"), ""); // Remove any remaining garbage url = url.replace(/[&;]$/, ""); return url; }</pre></p>
P粉239164234
P粉239164234

reply all(2)
P粉163465905

Modern browsers provide the URLSearchParams interface to handle search parameters. This interface has a delete method to delete parameters based on their names.

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(`您的浏览器 ${navigator.appVersion} 不支持URLSearchParams`)
}
P粉506963842
"[&;]?" + parameter + "=[^&;]+"

Looks dangerous because the parameter 'bar' will match:

?a=b&foobar=c

In addition, if parameter contains any characters that have special meaning in regular expressions, such as '.', this regular expression will fail. And it's not a global regex, so only one instance of the parameter will be removed.

I wouldn't use a simple regex to do this, I would parse the parameters and discard the ones I don't need.

function removeURLParameter(url, parameter) {
    //如果你有一个location/link对象,最好使用l.search
    var urlparts = url.split('?');   
    if (urlparts.length >= 2) {

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = urlparts[1].split(/[&;]/g);

        //反向迭代可能会破坏性
        for (var i = pars.length; i-- > 0;) {    
            //字符串.startsWith的习惯用法
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
    }
    return url;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template