zjm1126 zjm1126 - 3 months ago 10
Javascript Question

How to get the anchor from the URL using jQuery?

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

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#")
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.