DEV Community

Cover image for How to append a string to URL?
Stackfindover
Stackfindover

Posted on • Edited on

How to append a 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.

How to append string to URL 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;
      }
    }
Enter fullscreen mode Exit fullscreen mode

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.

How to append string to URL 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>
Enter fullscreen mode Exit fullscreen mode

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.

Thanks for reading how to append string to URL :)

Source URL: How to append string to URL?

Top comments (0)