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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 08:50:09660browse

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

Modifying Query String Parameters Dynamically

In web development, it's often necessary to manipulate the query string parameters in a URL for various reasons. Using JavaScript and jQuery, this can be achieved with ease. Here's how to add or update a query string parameter:

Adding Query String Parameter

If the query string parameter does not exist in the URL, you can simply append it using the following syntax:

var newURL = window.location.href + "&parameter=value";

This appends the parameter "parameter" with the value "value" to the existing URL.

Updating Query String Parameter

If the parameter is already present in the URL, you can update its value using a regular expression. Here's a helper function that accomplishes this:

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;
  }
}

This function takes the original URI, the key of the parameter to update, and its new value. It replaces the existing value of the parameter with the new one, or appends the parameter to the URI if it doesn't exist.

The above is the detailed content of How Can I Dynamically Add or Update Query String Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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