Parsing query strings for GET data in JavaScript

The Hypertext Transfer Protocol (HTTP) defines three methods to send data to a server — GET, POST, and PUT. GET requests append their data to the end of the URL in the form of a list of key–value pairs known as a query string — for example:

http://example.com/?key1=value1&key2=value2

In JavaScript this part of the URL can be accessed easily through the location.search property. However, naïve attempts to parse and decode this information often fail to take into account several issues — for example, the same key may occur multiple times, spaces may be encoded either as plus signs or the escape sequence %20, and semicolons may be used as separators instead of ampersands. QueryData handles these issues and makes the GET data available in a convenient format.

Download QueryData

Download one of the files below and upload it to your web server.

File Size Description
QueryData.js 2,568 bytes Full version, with comments
QueryData.compressed.js 689 bytes Compressed version

Link to the file using a script element in the head of your page:

1
<script type="text/javascript" src="QueryData.js"></script>

Using QueryData

To access the GET data from the page URL’s query string, create a new instance of QueryData with no parameters:

1
2
// extract the GET data
var getData = new QueryData();

The object that is returned has as its keys and values the keys and values from the GET data. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// check whether the 'debug' parameter was set
if ('debug' in getData){

  // check the value of the 'debug' parameter
  if (getData.debug == 'all'){

    // the 'debug' parameter was set to 'all'

  }else{

    // the 'debug' parameter was set to some other value

  }

}

QueryData isn’t limited just to parsing the page URL’s query string. An alternative query string can be passed as a parameter:

1
2
// parse a query string
var data = new QueryData('key1=value1&key2=value2');

Handling duplicate keys

A key may occur multiple times in a query string (for example, as a result of a form containing a ‘select’ element with the ‘multiple’ attribute set). By default, QueryData overwrites earlier values with later values for the same key, but setting its optional second parameter to ‘true’ causes it instead to create an array of values for each key:

1
2
3
4
5
6
7
8
9
// extract the GET data
var getData = new QueryData(location.search, true);

// loop over the values of the 'features' parameter
for (var index = 0; index < getData.features.length; index ++){

  // do something with getData.features[index]

}

Where now?

Found this useful? Share it:

Also in JavaScript: