Parse Query String Into Associative Array With JavaScript

So, there are lots of functions out there to do this, but this one is my favorite for a couple of reasons.

  1. It parses the entire query string as soon as you call the function, whereas other functions require passing in a parameter which the value for the parameter is then extracted from the query string
  2. It parses the query string into an associative array so key value pairs are easy to access later on.

function parseQuery() {
var queryAsAssoc = new Array();
var queryString = unescape(top.location.search.substring(1));
var keyValues = queryString.split(/&/);
for (var i in keyValues) {
    var key = keyValues[i].split(/=/);
    queryAsAssoc[keyValues[0]] = keyValues[1];
}
return queryAsAssoc;
}

Where might this be useful?

I might use this in combination with swfobject for a page that dynamically loads .swf files.

swfobject.embedSWF(parseQuery()['flash'] ||        "http://www.youtube.com/v/u_f7LF3IiKI&hl=en&fs=1","flash", "225",     "182", "9.0.0", false);

Examples

flash content

See this in action by checking out some of my other favorite songs.

No Trackbacks

You can leave a trackback using this URL: http://keithnorm.com/2008/12/30/parse-query-string-into-associative-array-with-javascript/trackback/

2 Comments

  1. Quinny

    This code: for (var i in keyValues) { var key = keyValues[i].split(/=/); queryAsAssoc[keyValues[0]] = keyValues[1]; } needs to be: for (var i in keyValues) { var key = keyValues[i].split(/=/); queryAsAssoc[key[0]] = key[1]; }

    Posted January 12, 2011 at 7:20 pm | Permalink
  2. wt

    a typo in your page code: queryAsAssoc[keyValues[0]] = keyValues[1]; should be queryAsAssoc[key[0]] = key[1];

    Posted June 23, 2011 at 4:00 pm | Permalink

Post a Comment

Your email is never shared. Required fields are marked *

*
*