How to append string to URL?

In this post, I will be able to allow you to skills to feature or update query string parameter to current URL using JavaScript and also, you’ll skills to feature query string to the current URL without reloading page.

Example 1

    function updateQueryStringParameter(url, key, value) {
      var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
      var separator = url.indexOf('?') !== -1 ? "&" : "?";
      if (url.match(re)) {
        return url.replace(re, '$1' + key + "=" + value + '$2');
      }
      else {
        return url + separator + key + "=" + value;
      }
    }

In above example, you’ll get to pass three argument, first are going to be your current URL and second are going to be key which you would like to update and last argument are going to be the worth of key.

Function will return you a replacement URL with updated query string.

Example 2

Using below line of code, you’ll add query string to current URL without reloading page.

 <button onclick="updateURL();">Update</button>
  <script type="text/javascript">
    function updateURL() {
      if (history.pushState) {
          var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?query=hello';
          window.history.pushState({path:newurl},'',newurl);
      }
    }
  </script>

In above example, history object of the DOM window is employed to supply 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.

Table of Contents

    Leave a Comment