我需要url的哈希值…
var hash = window.location.hash;
怎么去掉#
符号呢?
就这么简单。
var hash = window.location.hash.substr(1)
也有这两个返回完全相同的值:
var hash = window.location.hash.slice(1)
var hash = window.location.hash.substring(1)
String.slice()
稍后被添加到规范中,尽管这可能不重要。
使用下面提到的replace也是一个选项。
如果window.location.hash
字符串为空,这些选项都不会抛出错误或警告,因此它实际上取决于您的偏好使用。
你可以这样做-
hash = hash.replace(/^#/, '');
直接剪掉第一个字符:
var hash = window.location.hash.slice(1);
你可以直接做
var hash = window.location.hash.slice(1);
请注意,如果位置中没有散列,则不会产生错误,它只返回""
。
window.location.href.substr(0, window.location.href.indexOf('#'))
就可以了