Getting #id from current url

I am looking for a way to get the #anchor part from the current URL using JavaScript. For instance:

http://my-page.com/index.html#contact-us

Will return contact-us.

I could split the URI into a final one #, and then take the last fragment, but I'm looking for a slightly nicer and cleaner sentence. A natural function (jQuery?) Would be great, but I think I ask too much.

+5
source share
3 answers

Use location.hash:

location.hash.slice(1);

#, .slice(1). URL-, <a>, href, , protocol, hostname, hash .. jQuery:

$('a').attr('href', url)[0].hash;
+11

location.hash.replace(/^#/, "")

+2

If you are working with a variable:

var url = "http://my-page.com/index.html#contact-us";

var hash = url.substring(url.indexOf("#") + 1);
+1
source

All Articles