jQuery 从 window.location.hash 中删除 #

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3376010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:20:10  来源:igfitidea点击:

removing the # from window.location.hash

jquerywindow.location

提问by circey

I have this simple script:

我有这个简单的脚本:

$(document).ready(function(){

var $yoyo = window.location.hash;

alert($yoyo);

});

But I need to get rid of the # symbol as I'll be using the variable to locate div ids. I've tried using .remove('#') but that doesn't seem to be working.

但是我需要去掉 # 符号,因为我将使用该变量来定位 div id。我试过使用 .remove('#') 但这似乎不起作用。

Many thanks in advance!

提前谢谢了!

回答by Matthew Flaschen

var $yoyo = window.location.hash.substring(1);

This simply means we're taking a substring consisting of character 1 (0-indexed, so second) onwards. See the substringdocs.

这只是意味着我们正在使用一个由字符 1(0 索引,所以第二个)组成的子字符串。请参阅子字符串文档。

回答by Mike Sherov

var $yoyo = window.location.hash.replace("#", "");

.remove()is a jQuery dom manipulation function. .replace()is a native javascript function that replaces a string with another string inside of a string. From W3Schools:

.remove()是一个 jQuery dom 操作函数。.replace()是一个原生的 javascript 函数,它用字符串中的另一个字符串替换一个字符串。来自 W3Schools:

<script type="text/javascript">

var str="Visit Microsoft!";
document.write(str.replace("Microsoft", "W3Schools"));

</script>

回答by Anurag

$yoyo.substr(1)