How to get the hash value from the browser URL using JavaScript?

August 25, 2021 - 1 min read

To get the hash value from the browser URL, you can use the location.hash property from the global window object using JavaScript.

For example, let's say we have a URL called https://mywebsite.com#portfolio in the browser.

As you can see that after the .com there is a string after the # symbol (hash symbol). To get that value from the browser URL we can use the window.location.hash property in JavaScript.

It can be done like this,

// Get the hash value from the browser URL
const hashValue = window.location.hash;

console.log(hashValue); // #portfolio
  • The property returns the hash value with the hash symbol as its prefix.

See the above code live in this codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.