How to Modify URL Without Reloading the Page Using JavaScript

Here are two ways to modify the URL without reloading the page in JavaScript.

  1. Using the replaceState() function
  2. Using the pushState() function

Method 1: Using the replaceState() function

The replaceState() function is “used to modify the current history entry and replace the properties of the state with ones in the passed parameters.”

<!DOCTYPE html>
<html>

<head>
  <title>Replace State Demo</title>
  <script type="text/javascript">
    function changeUrl() {
      history.replaceState({}, "", "/new-url");
      document.getElementById('urlDisplay').innerHTML = window.location.href;
    }
 </script>
</head>

<body>
  <h1 style="color: red;">Current URL:</h1>
  <p id="urlDisplay"></p>
  <button onclick="changeUrl()">Change URL</button>

  <script type="text/javascript">
    document.getElementById('urlDisplay').innerHTML = window.location.href;
 </script>
</body>

</html>

Before clicking the button

Before clicking the button

After clicking the button

After clicking the button

Method 2: Using the pushState() function

The pushState() method is “used to add a new history entry with the properties passed as parameters.” This function will change the current URL to the new URL without reloading the page.

<!DOCTYPE html>
<html>

<head>
  <title>Push State Demo</title>
  <script type="text/javascript">
    function changeUrl() {
      history.pushState({}, "", "/new-url");
      document.getElementById('urlDisplay').innerHTML = window.location.href;
    }
 </script>
</head>

<body>
  <h1 style="color: red;">Current URL:</h1>
  <p id="urlDisplay"></p>
  <button onclick="changeUrl()">Change URL</button>

  <script type="text/javascript">
    document.getElementById('urlDisplay').innerHTML = window.location.href;
 </script>
</body>

</html>

Before clicking the button

Before clicking the button using pushState

After clicking the button

After clicking the button using pushState

That’s it.

Leave a Comment