How to get the anchor from the URL using jQuery?

How to get the anchor from the URL using jQuery?

I have a URL that is like:

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


Solution 1:

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

var url = "";
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 = "", 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.

Solution 2:

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 =;

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

var url = '';
var hash = url.split('#').pop();

If you’re using jQuery, use this:

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

Solution 3:



to retrieve everything beyond and including the #

Related:  JavaScript get TextArea input via .value or .innerHTML?

Solution 4:

jQuery style:


Solution 5:

You can use the following “trick” to parse any valid URL. It takes advantage of the anchor element‘s special href-related property, hash.

With jQuery

function getHashFromUrl(url){
    return $("<a />").attr("href", url)[0].hash.replace(/^#/, "");
getHashFromUrl(""); // a_1

With plain JS

function getHashFromUrl(url){
    var a = document.createElement("a");
    a.href = url;
    return a.hash.replace(/^#/, "");
getHashFromUrl(""); // a_1

Solution 6:

If you just have a plain url string (and therefore don’t have a hash attribute) you can also use a regular expression:

var url = ""  
var anchor = url.match(/#(.*)/)[1]