Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you define a fragment identifier?

The fragment identifier is a string after URI, after the hash, which identifies something specific as a function of the document. For a user interface Web document such as HTML poage, it typically identifies a part or view. For example in the object http://foo/bar#frag. the string "frag" is the fragment identifier.

How do I get a Windows location hash?

Alternatively, if you need a hash value for the current window URL, you can just use window. location. hash , which returns a string containing a '#' , followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this returns an empty string, "" .

What is hash fragment?

A hash sign (#) in a URL is referred to as a fragment. Historically, URL fragments have been used to automatically set the browser's scroll position to a predefined location in the web page. In that sense, if a URL refers to a document, then the fragment refers to a specific subsection of that document.


No need for 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 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);