How to add or update query string parameter to current url in Javascript

How to add or update query string parameter to current url in Javascript

In this post, I will let you know how to add or update query string parameter to current url using Javascript and also you will know how to add query string to the current url without reloading page.

Example 1
  1. function updateQueryStringParameter(uri, key, value) {
  2.      var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  3.      var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  4.      if (uri.match(re)) {
  5.      return uri.replace(re, '$1' + key + "=" + value + '$2');
  6.      }
  7.      else {
  8.      return uri + separator + key + "=" + value;
  9.      }
  10.     }

In above example, you will need to pass three argument, first will be your current url and second will be key which you want to update and last argument will be the value of key.

Function will return back you a new url with updated query string.

Example 2

Using below line of code, you can add query string to current url without reloading page.

  1. <button onclick="updateURL();">Update</button>
  2. <script type="text/javascript">
  3. function updateURL() {
  4. if (history.pushState) {
  5. var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?param=hi';
  6. window.history.pushState({path:newurl},'',newurl);
  7. }
  8. }
  9. </script>

In above example, history object of the DOM window is used to provide access to the browser's history.

pushState method is used to add or modify history entries and it takes three parameters : a state object, a title and a URL.

Phone: (+91) 8800417876
Noida, 201301