cppit
cppit

Reputation: 4564

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 = …

Upvotes: 242

Views: 214385

Answers (8)

Musa
Musa

Reputation: 97727

No need for jQuery

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

Since String.prototype.substr is deprecated use substring instead.

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

Upvotes: 644

Arthur Shlain
Arthur Shlain

Reputation: 1129

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);

Upvotes: 3

kmario23
kmario23

Reputation: 61505

It's very easy. Try the below code

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

Upvotes: 8

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27525

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

Upvotes: 5

JoyGuru
JoyGuru

Reputation: 1833

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

Upvotes: 8

Rohit L
Rohit L

Reputation: 1561

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);

Upvotes: 2

Talha
Talha

Reputation: 19282

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

Upvotes: 13

Ahsan Khurshid
Ahsan Khurshid

Reputation: 9469

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

Upvotes: 37

Related Questions