How to get the anchor from the URL using jQuery?

zjm1126 picture zjm1126 · Aug 24, 2010 · Viewed 200.4k times · Source

I have a URL that is like:

www.example.com/task1/1.3.html#a_1

How can I get the a_1 anchor value using jQuery and store it as a variable?

Answer

Silvio Delgado picture Silvio Delgado · Apr 9, 2012

For current window, you can use this:

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

To get the hash value of the main window, use this:

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

If you have a string with an URL/hash, the easiest method is:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

var hash = $(location).attr('hash');