How to remove the hash from window.location (URL) with JavaScript without page refresh?

The replaceState() method replaces the current history entry with the state objects, title, and URL passed as method parameters. This method is useful when you want to update the current history entry's state object or URL in response to a user action.

To remove the hash URL, use the history API's replaceState method to remove the hash location.


The syntax for the replaceState() method is as follows −

window.history.replaceState(stateObj,"unused", "url")

The function will take three parameters. They are −

  • stateObj − This parameter is associated with history entry which is passed to the replace method. This parameter can be null.

  • URL − ReplaceState throws an exception if the new URL is not of the same origin as the current URL.

Example 1

This example demonstrates how the hash is removed from URL in JavaScript −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scal=1.0"> <title>Remove Hash from URL</title> </head> <body style="text-align: align-self: start;"> <h1 style="color: orange">Tutorials Point</h1> <p>Removing the hash from window.location with JavaScript without page refresh </p> <p>modifying the current history state can also be done </p> <button onclick="modState()"> History state Modification </button> <button onclick="remHash()"> Remove hash from url </button> <script> function modState() { let stateObj = { id: "100" }; window.history.replaceState(stateObj, "Untitled-1", "/answer#Untitled-1.html"); } function remHash() { var uri = window.location.toString(); if (uri.indexOf("#") > 0) { var clean_uri = uri.substring(0, uri.indexOf("#")); window.history.replaceState({}, document.title, clean_uri); } } </script> </body> </html>

Updated on: 26-Aug-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started