Is there a better way to remove parameters from a URL string's query string than standard JavaScript using regular expressions?
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!
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; }
Modern browsersprovide 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.