Categories
JavaScript Answers

How to modify a query string without reloading the page with JavaScript?

Spread the love

Sometimes, we want to modify a query string without reloading the page with JavaScript.

In this article, we’ll look at how to modify a query string without reloading the page with JavaScript.

How to modify a query string without reloading the page with JavaScript?

To modify a query string without reloading the page with JavaScript, we can use the history.pushState method.

For instance, we write

const newUrl =
  window.location.protocol +
  "//" +
  window.location.host +
  window.location.pathname +
  "?myNewUrlQuery=1";
window.history.pushState({ path: newUrl }, "", newUrl);

to create the newUrl URL string.

Then we call pushState with { path: newUrl } and newUrl to navigate to newUrl without reloading the page.

We get the current URL data from window.location.

We get the protocol with window.location.protocol.

host has the hostname.

pathname has the path before the query string.

Conclusion

To modify a query string without reloading the page with JavaScript, we can use the history.pushState method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.