user1661548
user1661548

Reputation:

How to read the #hash (or fragment identifier) of the current page URL?

If I am on https://www.website.com/#something, how can I return the hash value "something" from the URL?

Upvotes: 10

Views: 23007

Answers (4)

DerpyCoder
DerpyCoder

Reputation: 135

You could use this

h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]

Upvotes: -1

Jaya Mayu
Jaya Mayu

Reputation: 17247

update

As there is a built in method to get the hash via DOM above answer is not appropriate

   var hashTag = window.location.hash
   alert(hashTag);

will do the magic.

Old answer

You can do something as below if you have multiple hashes in your url

//var href = location.href; // get the url in real worl scenario
var href = "www.bla.com#myhashtag"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
    afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);

Here is an example Live Fiddle

Upvotes: 1

Eli
Eli

Reputation: 14827

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;

Upvotes: 4

Sandeep
Sandeep

Reputation: 2121

window.location.hash its that simple.

donot use all those methods which consume CPU and effects performance.

If DOM provides something predefined use it first.

To pass value to PHP please do and ajax call to php.

var hash = window.location.hash;

$.ajax({
    url: 'someurl.php',
    data: {hash: hash},
    success: function(){}
})

Upvotes: 17

Related Questions