| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Thursday, June 18, 2009

EVEN Better JavaScript Query String Parsing

A while back, I posted an article on how to parse the query string in JavaScript. Binny V A, a much more proficient JavaScripter than I, suggested a method by which one could create an associative array from the query string so that you can reference the variable through an array instead of having to declare individual variables in the script.

At the time, it was a bit out of my grasp to understand the subtlety of his code, I've since become a bit more knowledgeable concerning associative arrays and I've been able to whittle down my previous code example into something much more elegant.

I present to you for your scripting pleasure, the Better JavaScript Query String Parser:
var a = location.search.slice(1).split("&"), GET = [];
for (i in a) { GET[a[i].split("=")[0]] = a[i].split("=")[1]; }

This will return an array named "GET" that consists of query string variables that can be referenced by the following example:
http://example.com/index.html?id=1001&fname=Ben&lname=Bradley

alert("id = " + GET["id"]);
alert("first name = " + GET["fname"]);
alert("last name = " + GET["lname"]);

0 comments: