8

我需要来自 url 的哈希值...

var hash = window.location.hash;

那么如何摆脱#标志呢?

4

5 回答 5

12

就这么简单。

var hash = window.location.hash.substr(1)

还有这两个返回完全相同:

var hash = window.location.hash.slice(1)
var hash = window.location.hash.substring(1)

String.slice()稍后将其添加到规范中,尽管这可能并不重要。

如下所述使用替换也是一种选择。

如果字符串为空,这些选项都不会引发错误或警告window.location.hash,因此它实际上取决于您的偏好使用什么。

于 2013-05-14T09:42:12.700 回答
6

你可以这样做 -

hash = hash.replace(/^#/, '');
于 2013-05-14T09:43:00.213 回答
1

只需剪下第一个字符:

 var hash = window.location.hash.slice(1);
于 2013-05-14T09:42:33.337 回答
0

你可以简单地做

 var hash = window.location.hash.slice(1);

请注意,如果该位置没有散列,它不会产生错误,它只会返回"".

于 2013-05-14T09:42:10.840 回答
0

window.location.href.substr(0, window.location.href.indexOf('#'))会成功的

于 2013-05-14T09:43:21.650 回答