Javascript 如何从 URL 获取片段标识符(哈希 # 后的值)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11662693/
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-24 06:41:26  来源:igfitidea点击:

How do I get the fragment identifier (value after hash #) from a URL?

javascriptjqueryurlurl-fragment

提问by cppit

Example:

例子:

www.site.com/index.php#hello

Using jQuery, I want to put the value helloin a variable:

使用 jQuery,我想把值hello放在一个变量中:

var type = …

回答by Musa

No need for jQuery

不需要 jQuery

var type = window.location.hash.substr(1);

回答by Ahsan Khurshid

You may do it by using following code:

您可以使用以下代码来完成:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

看演示

回答by Talha

var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
  hash = type[1];
alert(hash);

Working demo on jsfiddle

jsfiddle 上的工作演示

回答by JoyGuru

Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.

使用以下 JavaScript 从 URL 获取哈希 (#) 后的值。您不需要为此使用 jQuery。

var hash = location.hash.substr(1);

I have got this code and tutorial from here - How to get hash value from URL using JavaScript

我从这里得到了这个代码和教程 - How to get hash value from URL using JavaScript

回答by Manohar Reddy Poreddy

I had the URL from run time, below gave the correct answer:

我有运行时的 URL,下面给出了正确的答案:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

hope this helps

希望这可以帮助

回答by kmario23

It's very easy. Try the below code

这很容易。试试下面的代码

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});

回答by Ro Hit

Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...

基于 AK 的代码,这里是一个辅助函数。JS小提琴在这里(http://jsfiddle.net/M5vsL/1/)...

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);