Parsing a Querystring in JavaScript
28 May 2008
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([querystring])
-
Creates a new Querystring object, optionally passing a string
qsto parse. Ifqsis omitted, the querystring from the current page is used. - If
querystringis 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")
Constructor
Methods
- qs.get(name[, default_value])
-
Returns the value of querystring parameter
nameif it exists, ordefault_valueif it doesn't. - If
default_valueis omitted and parameternamedoesn't exist, returnsnull.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
trueif the querystring has a parametername, elsefalse.if (qs2.contains("name1")){ alert(qs2.get("name1"));}
Examples
- This font viewer is all done on the client-side, using Querystring.
- An earlier version of this code was adapted for use in this project.
References
RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax
Section 3.4, "Query"
Section 3.4, "Query"
HTML 4.01 Specification
Section 17.13.4.1, "Form content types: application/x-www-form-urlencoded"
Section 17.13.4.1, "Form content types: application/x-www-form-urlencoded"
Versions
- 1.3: Added "contains" function and fixed a syntax error. (Thanks to Bob Waycott & Stéphane Dorion.)
- 1.2.4: Overdue style changes, like semicolons at the ends of statements.
- 1.2.3: "name" was accidentally global instead of local. (Thanks to Ørnulf Risnes)
