Thursday, June 18, 2009

Javascript to get query params from url

This is one of those things that comes up from time to time that I always forget...

If you need some javascript to parse your url query parameters here it is:
var str="http://www.google.com?q=blah&vv=ha&test&nah=yeah"; // window.location.href
var regex = /[?&]([^=&]*)(?:=([^&]*))?/g;
var res, params = {};
while ((res = regex.exec(str)) != null)
{
params[res[1]] = res[2] || "n/a";
}

for (a in params)
{
document.write(a + "=" + params[a] + "<br/>");
}

results in:
q=blah
vv=ha
test=n/a
nah=yeah

Note I stuck n/a into the empty query parameters. You can do whatever you like. Also, don't use for in loops you can run into all types of issues.

0 comments:

Post a Comment