Categories
JavaScript Answers

How to append to URL and refresh page with JavaScript?

Spread the love

Sometimes, we want to append to URL and refresh page with JavaScript.

In this article, we’ll look at how to append to URL and refresh page with JavaScript.

How to append to URL and refresh page with JavaScript?

To append to URL and refresh page with JavaScript, we append to the window.location.href string.

For instance, we write

let url = window.location.href;
if (url.indexOf("?") > -1) {
  url += "&param=1";
} else {
  url += "?param=1";
}
window.location.href = url;

to append a substring to the url according to the value of url.

And then we set the new url string as the value of window.location.href to update the URL and refresh the page.

Conclusion

To append to URL and refresh page with JavaScript, we append to the window.location.href string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *