How to remove query string parameters in JavaScript?
P粉239164234
2023-08-20 18:46:10
<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>
Modern browsers provide the
URLSearchParams
interface to handle search parameters. This interface has adelete
method to delete parameters based on their names.Looks dangerous because the parameter 'bar' will match:
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.