Zar Zar - 1 month ago 8
Javascript Question

Getting the #id from current URL

I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript.
For example:


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


Would return
contact-us
.

I could split the URI at the eventual
#
and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.

Answer

Use location.hash:

location.hash.slice(1);

It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:

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