How to get the anchor from the URL using jQuery?

JavascriptJqueryUrlAnchor

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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');

Solution 2 - Javascript

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.

Solution 3 - Javascript

Use

window.location.hash

to retrieve everything beyond and including the #

Solution 4 - Javascript

jQuery style:

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

Solution 5 - Javascript

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("www.example.com/task1/1.3.html#a_1"); // a_1

With plain JS

function getHashFromUrl(url){
    var a = document.createElement("a");
    a.href = url;
    return a.hash.replace(/^#/, "");
};
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

Solution 6 - Javascript

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 = "www.example.com/task1/1.3.html#a_1"  
var anchor = url.match(/#(.*)/)[1] 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzjm1126View Question on Stackoverflow
Solution 1 - JavascriptSilvio DelgadoView Answer on Stackoverflow
Solution 2 - JavascriptNick CraverView Answer on Stackoverflow
Solution 3 - JavascriptRealView Answer on Stackoverflow
Solution 4 - JavascriptValentin EView Answer on Stackoverflow
Solution 5 - JavascriptDavid MurdochView Answer on Stackoverflow
Solution 6 - JavascriptDrewBView Answer on Stackoverflow