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.
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.
#
Use location.hash:
location.hash
location.hash.slice(1);
#, .slice(1). URL-, <a>, href, , protocol, hostname, hash .. jQuery:
.slice(1)
<a>
protocol
hostname
hash
$('a').attr('href', url)[0].hash;
location.hash.replace(/^#/, "")
If you are working with a variable:
var url = "http://my-page.com/index.html#contact-us"; var hash = url.substring(url.indexOf("#") + 1);