Gathering GET params from the URL
When a URL contains the GET params the keyed values can be extracted from the location.href or location.search
Here is a very concise example care of Jumper (efnet):
(function(){
for(var Q=QueryString={},
h=location.href,
s=h.substring(h.indexOf("?")+1),
qs=s.split("&"),
i=0,k,v;
k=qs[i++];
v=k.split("="),
Q[v[0]]=unescape(v[1]));
})()
The above example will create an object named QueryString which contains a key value pairs for each param in the Querystring.
Using the URL : http://www.google.com/search?num=100&hl=en&safe=off&q=javascript+querystring& each params can be reference :
- num :
QueryString.numorQueryString["num"] - 100
- hl :
QueryString.hlorQueryString["hl"] - en
- safe :
QueryString.safeorQueryString["safe"] - off
- q :
QueryString.qorQueryString["q"] - javascript+querystring
Please Note : The example above has been laied out to make it legible and would be better expressed :
(function(){for(var Q=QueryString={},h=location.href,s=h.substring(h.indexOf("?")+1),qs=s.split("&"),i=0,k,v;k=qs[i++];v=k.split("="),Q[v[0]]=unescape(v[1]));})()
Another one
Here's another example function, that makk wrote, that will give you all key value pairs of an url querystring.
/* deserializeUrl: returns object literal containing
all key value pairs of the url search part.
*/
function deserializeUrl() {
var ret = {};
var search = location.search.slice(1);
if (search) {
for (var pairs = search.split('&'), i = 0, l = pairs.length, pair; i < l; i++) {
pair = pairs[i].split('=');
key = decodeURIComponent(pair[0]);
val = decodeURIComponent(pair[1]);
if (key in ret) {
if (!(ret[key] instanceof Array)) {
ret[key] = [ret[key]];
}
ret[key].push(val);
} else {
ret[key] = val;
}
}
}
return ret;
}
/* Usage:
given an url like: http://www.aoe.com/uid?foo=bar&id=1&serv=foo&serv=makk
running `deserializeUrl' will rusult in the following:
var obj = deserializeUrl();
obj['foo'] which will contian 'bar'
obj['serv'] which will contain an array ['foo', 'makk']
obj['id'] which will contian '1'
note that '1' is not a number but a string
*/