Home > Web Front-end > JS Tutorial > How Can I Add or Update Query String Parameters in JavaScript?

How Can I Add or Update Query String Parameters in JavaScript?

Barbara Streisand
Release: 2024-12-04 21:01:12
Original
902 people have browsed it

How Can I Add or Update Query String Parameters in JavaScript?

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;
  }
}
Copy after login

Usage

To use the function, pass in the following arguments:

  • uri: The original URL with or without any query string parameters
  • key: The name of the query string parameter to add or update
  • value: The value to set for the parameter

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template