DP_QueryString

The DP_QueryString script creates a global object which provides the developer with simple access to values set in the query string (also called the “command line parameters” or “URL variables”). It also provides the capability to generate query strings from an object.

  • Full support for query strings where multiple parameters have the same name.
  • The object has methods to get any query string element by name or get all elements at once.
  • The object provides a method to generate query strings from a passed object.
  • Provides the ability to parse both the current (browser generated) query string and arbitrary query strings specified by the developer.

The extensions are self-contained and present an extremely small footprint. Only a single global object, “DP_QueryString”, is created.

This component requires a JavaScript (ECMAScript) 1.3 (or better) development environment and has been tested successfully on Internet Explorer 6+, Firefox 1+ and Opera 9+.

Download

The component is available from GitHub:

All downloads and code are covered by our Source Code Policy.

Usage

The script consists of a single JavaScript file with a .JS extension.

Importing the Library

The library must be imported before it is used. To import the library use the <script> tag. For example:

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

Your path may vary depending on the location of the script on your server.

Accessing the Object

Importing the script automatically creates a new, global JavaScript object called “DP_QueryString“. To use a method of the object call it directly:

var myVars = DP_QueryString.getAll();

See the Examples section for some sample code.

A Query String Primer

The query string (sometimes called the “command line”) is the portion of the URL after the file name to be returned and before a local target. In the following URL the bold area is the query string:

http://www.mysite.com/page.htm?param1=value1&param2=value2#LocalTarget

Query strings define values as name=value pairs separated by an ampersand (“&”). The above query string defines two parameters: param1, which has a value of “value1” and param2, which has a value of “value2”.

Some useful information to remember about query strings:

  • Values in query strings are commonly escaped, or encoded. This means that punctuation, spaces and other characters illegal in URLs have been replaced with standard escape sequences. For example a space character would be converted to “%20”.
  • Query string parameters are not required to have a value. Often only the existence of a parameter is used as a marker to indicate some state or value.
  • Query string parameters are not required to be unique. A single query string may contain any number of parameters which share the same name.

Properties and Methods

The DP_QueryString object contains no properties.

DP_QueryString methods available:

Note that in method/function signatures a pipe (“|”) indicates “OR” while arguments in square brackets are optional.

get()

Returns, in a specified style, the value(s) of the query string parameter specified by name.

Method Signature

get(Name, [ResultStyle], [QueryString])

Arguments

This method has three arguments:

  • Name: String, required. The name of the parameter to return.
  • ResultStyle: String, optional. Defaults to “array”. Specifies the way that values should be returned and how multiple parameters with the same name should be handled. Acceptable values are:
    • array: Default. All parameters are returned as an array of values.
    • first: Only the first value encountered for a parameter will be returned as a simple string.
    • last: Only the last value encountered for a parameter will be returned as a simple string.
    • list: All values for a parameters will be returned as a comma-separated list.
  • QueryString: String, optional. A valid query string to be parsed. If missing the current query string (obtained from location.search) will be used.

Return

Array, String or null. The returned value is determined by the ResultStyle. argument Empty parameters (parameters without values) are returned as empty strings. If the specified parameter does not exist null will be returned regardless of ResultStyle.

getAll()

Gets all available query string parameters. Can be used to examine or iterate over the query string and is useful for debugging purposes.

Method Signature

getAll([ResultStyle], [QueryString])

Arguments

This method has two arguments:

  • ResultStyle: String, optional. Defaults to “array”. See the get() method for details.
  • QueryString: String, optional. A valid query string to be parsed. If missing the current query string (obtained from location.search) will be used.

Return

Object. An object where each property=value corresponds to the parameter=value of the query string in the ReturnStyle specified. An empty object will be returned if there are no query string parameters available.

generate()

Converts the properties and values of a passed object to a query string.

Method Signature

generate(Object)

Arguments

This method has one argument:

  • Object: Object, Required. A simple, one dimensional object. The values contained in the object must be simple string values (or convertable to strings via the toString() method) or arrays. An array value will be converted to multiple parameters of the same name.

Return

String. A standard query string, preceeeded by a question mark (“?”) or, if an empty object were passed, an empty string.

Examples

As noted the script must be imported (<script type=”text/javascript” src=”DP_QueryString.js”></script>). Once the script has been imported the DP_QueryString object is ready for use.

The following examples will assume the following query string:

?test1=1&test2=1&test2=2&test3

Getting Parameter Values

Use the get() method to obtain the value of a named query string parameter. The get() method accepts as arguments the Name of the parameter to be returned and the ReturnStyle which determines how to return the results and how to manage multiple parameters of the same name.

To get the value of the “test1” parameter use:

DP_QueryString.get("test1");

This call will return an array with a single value, “1”.

A call to DP_QueryString.get(“test2”) would return an array with two elements (note that there are actually two values associated with that name). Finally note that the parameter “test3” has no value. The call DP_QueryString.get(“test3”) would result in an array with one element containing the empty string.

A call to return a parameter that doesn’t exist will always result in a null value.

The use of the ResultStyle argument may need some clarification. This table presents the returned value for all possible permutations of the get() method for the sample query string (JavaScript literal notation (where braces represent an object and square brackets represent an array) is used to describe complex return values):

Parameter Name ReturnStyle
“array” (default) “first” “last” “list”
test1 [“1″,”2”] “1” “2” “1,2”
test2 [“2”] “2” “2” “2”
test3 [“”] “” “” “”

Note that the “First” and “Last” options may in fact fail to return all related data. These options exist to allow developer’s to easily use the results (without having to resort to array handling) or for certain special cases. It reccommended not to use these options unless you fully understand the issues that may result.

Using Parameter Values

As noted requested parameters that don’t exist will return null. Considering this checking for parameter existence is very easy:

	if ( DP_QueryString.get("test1") ) {
		... Parameter exists! ...
	} else {
		... Parameter does not exist! ...
	};
	

If the parameter exists the default behavior is to return an array with the parameter value(s). To use the first value found you can do this:

DP_QueryString.get("test2")[0]

Instead you could also use the ResultStyle argument to only return the first value found for a parameter as a string. You could then do this:

DP_QueryString.get("test2", "first")

You may loop over multiple values associated with a single name as you would any array. The following code illustrates checking for the existence of a parameter and then looping over and presenting all the values associated with it:

	var CurParam = DP_QueryString.get("test2");
	if ( CurParam ) {
		for ( var Cnt = 0; Cnt < CurParam.length; Cnt++ ) {
			document.write(CurParam[Cnt] + "<br>");
		};
	} else {
		... Parameter does not exist! ...
	};
	

Getting All Parameter Values

To retrieve all parameter values use the getAll() method. The method returns an object where the properties of the object correspond to the available parameters of the query string.

This method accepts the same ReturnStyle argument as the get() method. For the sample query string getAll() would result in the following:

ReturnStyle Resulting Object
“array” (default) { test1 : [“1”], test2 : [“1”, “2”], test3 : [“”] }
“first” { test1 : “1”, test2 : “1”, test3 : “” }
“last” { test1 : “1”, test2 : “2”, test3 : “” }
“list” { test1 : “1”, test2 : “1,2”, test3 : “” }

The resulting object can be very useful for debugging. Note also that the object, presumably after some modification, could be used as input to the generate() method. Using these two methods you can easily pass information between multiple pages.

Generating a Query String

The generate() method accepts an object and attempts to convert it to a query string representation. The following rules are apply:

  • The object’s property names must be valid query string parameter names.
  • The object properties must contain either simple strings or simple, single-dimensional arrays.
  • Properties with string values will be converted to parameters in the form of propName=propValue. Array values will be converted to multiple parameters of the same name in the form of propName=propValue[1]&propName=propValue[2]…&propName=propValue[n]. For puposes of query string generation there is no difference between a property containing a simple string and a property containing an array with only one element.

To create our sample query string above we might do the following:

	var NewOb = new Object();
	NewOb.test1 = 1;
	NewOb.test2 = new Array();
		NewOb.test2[0] = 1;
		NewOb.test2[1] = 2;
	NewOb.test3 = null;
	var MyQueryString = DP_QueryString.generate(NewOb);
	

The same query string could be generated in JavaScript literal notation like so:

	var NewOb = { test1:1, test2:[1,2], test3 }
	var MyQueryString = DP_QueryString.generate(NewOb);
	

As noted the results of the getAll() method can be modified and then used as input to the generate() method. This is a powerful technique to simplify state management across multiple pages.

Here’s a simplified example using our sample query string. If the parameter “test3” exists this script will add one to the value of “test1”, add another value to “test2” and remove “test3”. Finally it will update the page’s query string which should reload the page with the new values:

	if ( DP_QueryString.get("test3") ) {
			// Get the query string values
		var CurQS = DP_QueryString.getAll();
			// Change the value of "test1"
		CurQS.test1 = DP_QueryString.get("test1")[0] + 1;
			// Add another value to "test2"
		CurQS.test2[CurQS.test2.length] = 3;
			// Remove "test3"
		CurQS.test3 = undefined;
			// Update the page's query string
		location.search = DP_QueryString.generate(CurQS);
	};
	

Generated query strings can be used to construct page links, form action values and modify the location of the current page.

Revision History

June 8, 2013

  • Initial GITHUB release.

July 01, 2006

  • Initial Release

1 Comment

Comments are closed.