繁体   English   中英

使用Javascript从网址获取空哈希值

[英]Get empty hash value from url with Javascript

使用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 '';

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

您的方法工作正常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM