简体   繁体   中英

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

Example:

www.site.com/index.php#hello

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

var type = …

不需要 jQuery

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

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

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

It's very easy. Try the below code

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

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

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

Based on AK'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);

Get fragment of current document location

var hash = window.location.hash;

Get fragment from string

 // absolute var url = new URL('https://example.com/path/index.html#hash'); console.log(url.hash); // relative (second param is required, use any valid URL base) var url2 = new URL('/path/index.html#hash2', 'http://example'); console.log(url2.hash);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM