Akshat Mittal
Akshat Mittal

Reputation: 827

How to get #hash value in a URL in JS

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.

Upvotes: 23

Views: 47068

Answers (7)

user3713526
user3713526

Reputation: 481

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

Upvotes: 1

nishantkyal
nishantkyal

Reputation: 814

The URLSearchParams class can be reused for this purpose.

var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');

Upvotes: 17

xdazz
xdazz

Reputation: 160833

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

// usage
var hash = getHashValue('hash');

Upvotes: 51

abuduba
abuduba

Reputation: 5042

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

Upvotes: 2

Musa
Musa

Reputation: 97672

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 .

Upvotes: 5

RameshVel
RameshVel

Reputation: 65857

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655129

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"]]

Upvotes: 1

Related Questions