21

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.

Akshat Mittal
  • 777
  • 3
  • 12
  • 28

7 Answers7

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

// usage
var hash = getHashValue('hash');
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 2
    This results everything after `hash=` – Akshat Mittal Aug 12 '12 at 08:30
  • It should be noted that this will cause an error if there is no hash or if the key does not exist. [This is a more fail-safe version of the answer](http://jsfiddle.net/8gJCY/). – Hectron Feb 18 '14 at 20:09
  • @xdazz: as Hectron said, a TypeError gets raised if there is no hash, so you should check the length of the array returned by `match` method and only index this array if its length is greater than or equal to 2. If not, you should return an empty string or null (or undefined). – Sk8erPeter May 02 '15 at 00:49
  • It should also be noted that "key" will be interpreted by the RegEx parser, so having a legit key containing a dot or a single brace this will lead to results differing from expectation or even errors – Florian Loch Jul 16 '16 at 09:36
  • Should correct like: return matches && matches.length === 2 ? matches[1] : null; – GhostCKY Mar 16 '19 at 18:16
17

The URLSearchParams class can be reused for this purpose.

var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');
nishantkyal
  • 814
  • 1
  • 10
  • 8
  • 5
    Or you can also use `window.location.hash.slice(1)` instead. – Wong Jia Hau Aug 05 '19 at 08:32
  • 2
    That code is incorrect through. Rather than replacing "#" by "?" it should be removing the "#". So replace replace("#","?") by slice(1) – Clox Apr 01 '20 at 19:49
  • @Clox Well no, that would just merge the first key in the hash section with the last value in the parameter section, or merge it with the path. Either # needs to be replaced by ? (if there are no url parameters) or with & (if there are already parameters). But regardless this is a bad way to do it because youll pull url parameters as well. – B T May 01 '21 at 18:34
5

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 .

Musa
  • 96,336
  • 17
  • 118
  • 137
2
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
abuduba
  • 4,986
  • 7
  • 26
  • 43
1

Split on & and then on =:

pairs = location.hash.substr(1).split('&').map(function(pair) {
    var kv = pair.split('=', 2);
    return [decodeURIComponent(kv[0]), kv.length === 2 ? decodeURIComponent(kv[1]) : null];
})

Here pairs will be an array of arrays with the key at 0 and the value at 1:

[["hfh","fdg"],["hash","value2x"]]
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

If you are doing extensive url manipulations, then you shoud check out JQuery URL plugin.

To access the params in url hashes

    $.url('http://www.google.com/#hfh=fdg&hash=value2x').fparam('hash');

or if its current url

    $.url().fparam('hash');

Hope it helps

RameshVel
  • 64,778
  • 30
  • 169
  • 213
1

If url has ?: http://www.google.com/#?hash=value2x

The code can be:

const url = 'http://www.google.com/#?hash=value2x';
new URLSearchParams(
  (
    new URL(url)
  ).hash.slice(1).split('?')[1]
).get('hash');

Or if url has no ?:

const url = 'http://www.google.com/#hash=value2x';
(new URLSearchParams((new URL(url)).hash.slice(1))).get('hash')
user3713526
  • 435
  • 7
  • 16