Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get #hash value in a URL in JS

Tags:

javascript

url

For example, I have a URL as :

http://www.google.com/#hash=value2x

I want a js code to return just value2x. I tried location.hash.split('=')[1] but that results the first hash value like if url is

http://www.google.com/#hfh=fdg&hash=value2x

It returns fdg&hash. I want just the value of hash.

NO jQuery Please.

Thanks for the help in advance.

like image 649
Akshat Mittal Avatar asked Aug 12 '12 08:08

Akshat Mittal


4 Answers

function getHashValue(key) {
  var matches = location.hash.match(new RegExp(key+'=([^&]*)'));
  return matches ? matches[1] : null;
}

// usage
var hash = getHashValue('hash');
like image 102
xdazz Avatar answered Sep 21 '22 21:09

xdazz


The URLSearchParams class can be reused for this purpose.

var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');
like image 21
nishantkyal Avatar answered Sep 19 '22 21:09

nishantkyal


How about

location.hash.split('hash=')[1].split('&')[0]

This will split the hash at hash= and take the value after hash= and before any other argument .

like image 32
Musa Avatar answered Sep 19 '22 21:09

Musa


location.parseHash = function(){
   var hash = (this.hash ||'').replace(/^#/,'').split('&'),
       parsed = {};

   for(var i =0,el;i<hash.length; i++ ){
        el=hash[i].split('=')
        parsed[el[0]] = el[1];
   }
   return parsed;
};

var obj= location.parseHash();
    obj.hash;  //fdg 
    obj.hfh;   //value2x
like image 27
abuduba Avatar answered Sep 20 '22 21:09

abuduba