10

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

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

4 Answers4

17

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(){}
})
Sandeep
  • 2,041
  • 21
  • 34
4

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

var hash = window.location.hash;
Eli
  • 14,779
  • 5
  • 59
  • 77
1

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

Jay Mayu
  • 17,023
  • 32
  • 114
  • 148
-1

You could use this

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