如何使用JavaScript检查URL中的#哈希?

JavaScript

神无神乐

2020-03-11

我有一些jQuery / JavaScript代码,仅当#URL中有哈希()锚链接时才要运行如何使用JavaScript检查此字符?我需要一个简单的包罗万象的测试,该测试可以检测如下URL:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

基本上是这样的:

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

如果有人能指出我正确的方向,那将不胜感激。

第554篇《如何使用JavaScript检查URL中的#哈希?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
樱Mandy 2020.03.11

This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }
Sam蛋蛋Itachi 2020.03.11

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink
GO村村 2020.03.11
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
逆天蛋蛋达蒙 2020.03.11
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; 
  }
}
LEY蛋蛋 2020.03.11
window.location.hash 

will return the hash identifier

达蒙阿飞斯丁 2020.03.11

输入以下内容:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
西里Mandy 2020.03.11
  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android