I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript. For example:
.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.
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.
3 Answers
Reset to default 13Use 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;
location.hash.replace(/^#/, "")
If you work with a variable:
var url = "http://my-page.com/index.html#contact-us";
var hash = url.substring(url.indexOf("#") + 1);