I’m looking for a way to retrieve the #anchor part from the current URL with JavaScript.
For example:
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.
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 asprotocol,hostname,hash, etc. jQuery example: