Projects » JavaScript » Querystring

Parsing a Querystring in JavaScript

28 May 2008
Version 1.3
Download: querystring.js
License: Simplified BSD

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

Constructor

new Querystring([querystring])
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 querystring 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")

Methods

qs.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.
qs.contains(name)
Returns true if the querystring has a parameter name, else false.
if (qs2.contains("name1")){ alert(qs2.get("name1"));}

Examples

References

RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax
Section 3.4, "Query"
HTML 4.01 Specification
Section 17.13.4.1, "Form content types: application/x-www-form-urlencoded"

Versions


Contact Information