How to get the anchor from the URL using jQuery?
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');
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.