我需要从URL中获取哈希值...
var hash = window.location.hash;
那么我该如何去掉井号(#)符号呢?
我需要从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(/^#/, '');
hash.replace('#','')
比 slice(1)
更安全。 - rabhash.replace(/^#/, '')
,以便仅删除前导的 #
,而不是哈希的一部分。 - MildlySerious只需切掉第一个字符:
var hash = window.location.hash.slice(1);
你可以简单地做
var hash = window.location.hash.slice(1);
""
。window.location.href.substr(0, window.location.href.indexOf('#'))
这行代码可以解决问题。