The Hypertext Transfer Protocol (HTTP) defines three methods that can 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://www.example.com/page.html?key1=value1&key2=value2
In JavaScript this part of the URL can be accessed through the location.search property. However, naïve attempts to retrieve this data fail to take into account several data encoding issues — for example, spaces may be encoded either as plus signs or the escape sequence %20, and the HTML 4.01 specification states that a semicolon may be used a separator instead of an ampersand. The function parseQueryString handles these issues and makes the data available in a convenient format, and isn't limited to query strings obtained from the document’s URL.
Using parseQueryString
| File | Size | Description |
|---|---|---|
| parseQueryString.js | 2599 bytes | Full version with comments |
| parseQueryString.compressed.js | 911 bytes | Compressed version |
Download one of the files listed above and upload it to your website. Link to it from your page with code such as:
<script type="text/javascript" src="parseQueryString.js"></script>
parseQueryString can accept one parameter — a query string — or be called without parameters to use the query string from the current document’s URL — for example, the following are equivalent:
var queryData = parseQueryString();
var queryData = parseQueryString(location.search);
The query string may start with a question mark, spaces may be encoded either as plus signs or the escape sequence %20, and both ampersands and semicolons are permitted as separators — for example, the following are equivalent:
var queryData = parseQueryString('a=b+c');
var queryData = parseQueryString('?a=b+c');
var queryData = parseQueryString('a=b%20c');
var queryData = parseQueryString('?a=b%20c');
parseQueryString returns an object whose property names and values correspond to the decoded query data. Because a single key may occur multiple times in a query string, the properties of the returned object consist of arrays of values. These can be accessed either by property names or through string indices — for example, the following are equivalent:
alert(queryData.key[0]);
alert(queryData['key'][0]);
var key = 'key';
alert(queryData[key][0]);
JavaScript’s for–in statement can be used to loop over all the keys — the following code displays all keys and their values:
var queryData = parseQueryString('?a=b+c');
for (var key in queryData){
alert('Key: ' + key + ' Values: [' + queryData[key] + ']');
}
Note that when a key specified in the URL does not have a defined value (that is, it is followed immediately in the URL by an ampersand or semicolon) it is given the empty string as a value (as if it was followed immediately in the URL by an equals sign and then an ampersand or semicolon).