Get hash value from URL with JavaScript/jQuery
This post will discuss how to get hash value from URL using JavaScript and Query.
1. Get hash value for any URL
With pure JavaScript, you can get hash value from a given using the indexOf()
and substring()
, as demonstrated below:
1 2 3 4 5 6 7 |
var url = "https://mail.google.com/mail/u/0/#inbox"; var index = url.indexOf("#"); if (index !== -1) { var hash = url.substring(index + 1); console.log(hash); } |
You can also use the split()
method with the pop()
method, as shown below:
1 2 3 4 5 |
var url = "https://mail.google.com/mail/u/0/#inbox"; var parts = url.split('#'); if (parts.length > 1) { console.log(parts.pop()); } |
2. Get hash value for the current URL
Alternatively, if you need a hash value for the current window URL, you can just use window.location.hash
, which returns a string containing a '#'
, followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this returns an empty string, ""
.
1 2 |
// Returns '#input' for 'https://www.techiedelight.com/#input' var hash = window.location.hash; |
With jQuery, you can use the .prop()
on the location
object to get the hash:
1 2 |
// returns '#input' for 'https://www.techiedelight.com/#input' var hash = $(location).prop('hash'); |
To extract only the fragment identifier of the URL without '#'
, you can use the substr()
method like:
1 2 3 4 5 6 7 |
// returns 'input' for 'https://www.techiedelight.com/#input' // with JavaScript var hash = window.location.hash.substr(1); // with jQuery var hash = $(location).prop('hash').substr(1); |
Here’s another solution using window.location.href
.
1 2 |
// returns 'input' for 'https://www.techiedelight.com/#input' window.location.href.split('#').pop(); |
That’s all about getting hash value from URL using JavaScript and Query.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)