检查url哈希是否存在

时间:2018-04-27 10:16:59

标签: javascript jquery uri uri.js

我想检查网址中是否有哈希值:

这应该返回true:

  

domain.com/balbla#hash

这应该返回false:

  

domain.com/balbla

所以我使用URI.js来获取哈希

var uriFragment = new URI(window.location.href).fragment();
if (uriFragment.length) {
    console.log('yep')
} else {
    console.log('nope')
}

但即使网址中没有哈希值,也永远不会返回 nope

2 个答案:

答案 0 :(得分:1)

为什么不直接使用location.hash

if(location.hash.length > 0) {
    console.log('yep')
}else {
   console.log('nop')
}

答案 1 :(得分:0)

下面的代码将以数组格式给出哈希标记列表。

var hash = window.location.hash;
    return result = hash.split('#').reduce(function (result, item) {
        var parts = item.split('=');
        result[parts[0]] = parts[1];
        return result;
    }, {});