search

Home  >  Q&A  >  body text

How to remove query string parameters in JavaScript?

<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粉239164234P粉239164234463 days ago498

reply all(2)I'll reply

  • P粉163465905

    P粉1634659052023-08-21 11:15:52

    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`)
    }

    reply
    0
  • P粉506963842

    P粉5069638422023-08-21 09:30:25

    "[&;]?" + 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;
    }

    reply
    0
  • Cancelreply