Projects » JavaScript » Querystring

Parsing a Querystring in JavaScript

30 March 2008
Version 1.2.4
Download: querystring.js

The Querystring class parses "name=value" pairs from a querystring with client-side JavaScript.

In web browsers you can access the querystring with client-side JavaScript, but there is no standard way to parse out the name/value pairs.

This code provides a "Querystring" object that can parse the current document's querystring, or any querystring passed to the constructor. When passing a string, do not include an initial "?".

This object may be useful for "Ajax" coding, either for getting values for the current page or parsing results sent back in querystring form.

API Reference

new Querystring([qs])
Creates a new Querystring object, optionally passing a string qs to parse. If qs is omitted, the querystring from the current page is used. If qs is passed, it should not begin with a "?".
// Parse the current page's querystring
var qs = new Querystring()

// Parse a given querystring
var qs2 = new Querystring("name1=value1&name2=value2")
Querstrying.get(name[, default_value])
Returns the value of querystring parameter name if it exists, or default_value if it doesn't. If default_value is omitted and parameter name doesn't exist, returns null.
var v1 = qs2.get("name1")
var v3 = qs2.get("name3", "default value")
Note: If a name appears more than once in a querystring only the last value is kept.

Examples

References

"RFC 1738 - Uniform Resource Locators (URL)"
Section 5, Page 18, "HTTP"
HTML 4.01 Specification
Section 17.13.4.1, "Form content types: application/x-www-form-urlencoded"

Versions


Contact Information