我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:

example.com/page.html #锚 example.com/page.html # anotheranchor

基本上是这样的:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}

当前回答

...或者有一个jquery选择器:

$('a[href^="#"]')

其他回答

我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。

 const hasHash = string => string.includes('#')

你也可以像这样从url中删除散列:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}

最后你可以把逻辑组合在一起:

if(hasHash(url)) {
 url = removeHash(url)
}
window.location.hash 

将返回哈希标识符

如果URI不是文档的位置,这个代码段将按照您的要求执行。

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

你可以使用现代JS解析url:

var my_url = new URL('http://www.google.sk/foo?boo=123#baz');

my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
​my_url.protocol; // "http:"
​my_url.search; // outputs "?doo=123"

没有哈希的url将返回空字符串。

function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}