Adding and Updating Query String Parameters with JavaScript
In web development, query string parameters are used to pass data to a server-side script or to modify the URL of a page. This is often done to add filters to a search query, track user traffic, or improve website analytics.
One common challenge is to update or add a query string parameter if it already exists or doesn't. To address this, a custom JavaScript function can be implemented.
Solution
Here's a JavaScript function that accomplishes the task:
function updateQueryStringParameter(uri, key, value) { var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&" : "?"; if (uri.match(re)) { return uri.replace(re, '' + key + "=" + value + ''); } else { return uri + separator + key + "=" + value; } }
Usage
To use the function, pass in the following arguments:
Example
Let's say you have a URL like http://example.com/search?query=test. To update the query parameter with the value new query, you would call the function as follows:
var updatedUri = updateQueryStringParameter('http://example.com/search', 'query', 'new query'); console.log(updatedUri); // Output: http://example.com/search?query=new query
If the parameter didn't exist in the original URL, it would be added:
var updatedUri = updateQueryStringParameter('http://example.com/search', 'new_param', 'new value'); console.log(updatedUri); // Output: http://example.com/search?new_param=new value
This function provides a convenient way to manipulate query string parameters in JavaScript, making it easy to add or update specific parameter values as needed.
The above is the detailed content of How Can I Add or Update Query String Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!