最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the #id from current URL - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked Jul 4, 2012 at 19:44 ZarZar 6,8829 gold badges56 silver badges76 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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;

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);
发布评论

评论列表(0)

  1. 暂无评论