For example, I have a URL as :
http://www.google.com/#hash=value2x
I want a js code to return just value2x
.
I tried
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
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 .
function getHashValue(key) {
var matches = location.hash.match(new RegExp(key+'=([^&]*)'));
return matches ? matches[1] : null;
}
// usage
var hash = getHashValue('hash');
The URLSearchParams class can be reused for this purpose.
var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');
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
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"]]