Zar Zar - 6 months ago 29
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.


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;