Parsing The Querystring with Javascript

By Peter A. Bromberg, Ph.D.

Peter Bromberg  

The client - side Javascript/JScript/ECMAScript model has a rich set of methods and properties related to the Page and Window objects. One of the most useful of these is the ability to parse the various components of the URL. But before we look at that, this might be a good time to review the methods and properties of the location object:

The Location object is part of a Window object and is accessed through the window.location property. It contains the complete URL of a given Window object, or, if none is specified, of the current Window object. All of its properties are strings representing different portions of the URL, which generally takes the following form:



<protocol>//<host>[:<port>]/<pathname>[<hash>][<search>]

You can create a Location object by simply assigning a URL to the location property of an object:

Code:
window.location = "file:///C:/Projects" or window.location = "http://www.yahoo.com"

The invocation of setting the window.location property immediately instructs the browser to perform the requested navigation.

PROPERTIES:

hash Property
The hash property is a string beginning with a hash (#), that specifies an anchor name in an HTTP URL.

Syntax: location.hash

This instructs the browser to load the requested page and scroll to the anchor tag designated by the hash value.

host Property
The host property is a string comprising of the hostname and port strings.

Syntax: location.host

hostname Property

The hostname property specifies the server name, subdomain and domain name (or IP address) of a URL.

Syntax: location.hostname

href Property

The href property is a string specifying the entire URL, and of which all other Link properties are substrings.

Syntax: location.href

pathname Property
The pathname property is a string portion of a URL specifying how a particular resource can be accessed.

Code: document.write(location.pathname)

This would produce : articles/todaysFeature.htm

port Property
The port property is a string specifying the communications port that the server uses.

Syntax: location.port

protocol Property
The protocol property is the string at the beginning of a URL, up to and including the first colon (:), which specifies the method of access to the URL, e.g. "http:", "mailto:", "ftp:", etc.

Syntax: location.protocol

search Property
The search property is a string beginning with a question mark that specifies any query information in an HTTP URL. This is the property we'll be working with in this article.

Syntax: location.search

METHODS

reload Method
The reload method forces a reload of the window's current document, i.e. the one contained in the Location.href property.

Syntax: location.reload([forceGet])

For example, onClick="window.location.reload(true)" would force a GET reload, ignoring the fact that the document may already be in the cache.

replace Method

The replace method replaces the current History entry with the specified URL. After calling the replace method, you cannot navigate back to the previous URL using the browser's Back button.

Syntax: location.replace(URL)

Now that we've gotten our quick refresher, let's look at one of many ways to create a Querystring processor that can be used in a manner not too much more complicated than the Request.Querystring("key") method we're so used to in the ASP object model:

<script>
function PageQuery(q) {
if(q.length > 1) this.q = q.substring(1, q.length);
else this.q = null;
this.keyValuePairs = new Array();
if(q) {
for(var i=0; i < this.q.split("&").length; i++) {
this.keyValuePairs[i] = this.q.split("&")[i];
}
}
this.getKeyValuePairs = function() { return this.keyValuePairs; }
this.getValue = function(s) {
for(var j=0; j < this.keyValuePairs.length; j++) {
if(this.keyValuePairs[j].split("=")[0] == s)
return this.keyValuePairs[j].split("=")[1];
}
return false;
}
this.getParameters = function() {
var a = new Array(this.getLength());
for(var j=0; j < this.keyValuePairs.length; j++) {
a[j] = this.keyValuePairs[j].split("=")[0];
}
return a;
}
this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key){
var page = new PageQuery(window.location.search);
return unescape(page.getValue(key));
}
function displayItem(key){
if(queryString(key)=='false')
{
document.write("you didn't enter a ?name=value querystring item.");
}else{
document.write(queryString(key));
}
}
</script>
<body onload="displayItem('name');">

I think most of this code should be self - explanatory; we are cracking the URL by passing the window.location.search portion into the PageQuery object, which simply splits the key-value pairs into arrays. Then we simply iterate the "collection" with the function prototype "getValue" returning the match. Finally , we unescape it in the utility accessor function "queryString".

If you put your name and email address in the fields below and press the SUBMIT button, your information will be appended to the querystring on the URL to the page that holds the above code, and displayed in the document body. You can get the code for this by simply viewing the source of the page that comes up. The code for the way we're sending it out is as follows:

<input type="text" name="txtName" id="txtName">Name<br>
<input type="text" name="txtEmail" id="txtEmail">Email<BR>
<input type="button" value="Submit" onclick="getURL(txtName.value, txtEmail.value);">
<script>
function getURL(sName, sEmail){
window.location ="http://www.nullskull.com/articles/querystringjs.htm?name="+sName+"&email="+sEmail;
}
</script>

Name
Email

Peter Bromberg is an independent consultant specializing in distributed .NET solutions in Orlando and a co-developer of the NullSkull.com developer website. He can be reached at info@eggheadcafe.com