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
- function updateQueryStringParameter(uri, key, value) {
- var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
- var separator = uri.indexOf('?') !== -1 ? "&" : "?";
- if (uri.match(re)) {
- return uri.replace(re, '$1' + key + "=" + value + '$2');
- }
- else {
- return uri + separator + key + "=" + value;
- }
- }
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 2Using below line of code, you can 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 + '?param=hi';
- window.history.pushState({path:newurl},'',newurl);
- }
- }
- </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.