使用Javascript从url中获取空哈希值

Get empty hash value from url with Javascript

本文关键字:获取 哈希值 url Javascript 使用      更新时间:2023-09-26

使用window.location.hash我得到这个:

http://example.com         --> ''
http://example.com#        --> ''
http://example.com#ahihah  --> '#ahihah'

然而,我需要区分这两种情况:

http://example.com         --> ''
http://example.com#        --> '#'
http://example.com#ahihah  --> '#ahihah'

因此,当url中没有哈希时(第一种情况),可以有一个空字符串,但如果有哈希符号,我希望有值'#'。这在JavaScript中可能吗?


我已经试过了。

var hash = window.location.hash;
var href = window.location.href;
if (hash !== '') {
  return link.hash;
}
if (href.slice(-1) === '#') {
  return '#';
}
return '';

但看起来是一种容易出错的方法。可能是url中的查询字符串以#结尾,并且函数将落入第二个返回'#'而不是''if中?

您的方法运行良好。

查询字符串中不能有#(它需要编码为%23,然后编码为href.slice(-1) === 3),因为这将被解释为哈希的开始,而不是查询字符串的一部分。