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

假如想象 提交于 2020-01-08 11:11:34

问题


Example:

www.site.com/index.php#hello

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

var type = …

回答1:


No need for jQuery

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



回答2:


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




回答3:


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




回答4:


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

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

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




回答5:


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

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

hope this helps




回答6:


It's very easy. Try the below code

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



回答7:


Based on A.K's code, here is a Helper Function. JS Fiddle Here (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);


来源:https://stackoverflow.com/questions/11662693/how-do-i-get-the-fragment-identifier-value-after-hash-from-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!