How to get hash value from URL using JavaScript

Many times we modify the web page elements depending on the hash (#) value of the current URL. It’s very effective way to pass a value with the URL and load the web page based on that value. Using JavaScript you can easily get the value after the hashtag (#) from the URL, there are no need to use jQuery. Also, you can get the hash value from href using simple JavaScript code.

The following JavaScript code will show how to get value with, after and before hashtag (#).

Assume that the current URL is –

Get value with hashtag (#): (#VideoTutorial)

var hash = location.hash;

Get value after hashtag (#): (VideoTutorial)

var hash = location.hash.substr(1);

Get hash value from href: (#VideoTutorial)
this.hash returns the hash value from href attributes of an anchor tag.

<a href="" onclick="alert(this.hash)">Get Hash</a>

Leave a reply