Zar Zar - 1 year ago 65
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:

Would return

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 Source

Use location.hash:


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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download