Home >Web Front-end >JS Tutorial >How to Remove a Query String Parameter in JavaScript Without Using Regular Expressions?
How can I delete a query string parameter in JavaScript without relying on regular expressions?
Instead of using a regular expression to delete a query string parameter, a more robust approach involves parsing the parameters. Here's an example implementation:
function removeURLParameter(url, parameter) { // Parse the URL into parts var urlparts = url.split('?'); // If there's no query string, return the original URL if (urlparts.length < 2) { return url; } // Split the query string into individual parameters var pars = urlparts[1].split(/[&;]/g); // Reverse iterate to ensure the order of items after splicing for (var i = pars.length; i--;) { // Check if the parameter starts with the specified prefix if (pars[i].lastIndexOf(encodeURIComponent(parameter) + '=', 0) !== -1) { // Remove the offending parameter pars.splice(i, 1); } } // Rebuild the query string var newQuery = (pars.length > 0 ? '?' + pars.join('&') : ''); // Rebuild the full URL return urlparts[0] + newQuery; }
This approach has several advantages:
The above is the detailed content of How to Remove a Query String Parameter in JavaScript Without Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!