navigation
 Monday, December 17, 2007

I've found myself writing more and more client-side script these days, and I recently came upon the need to parse the query string to determine some client-side behavior. Now, where's that handy QueryString collection I'm so used to working with in server-side code? What? There isn't one? Fine, I'll just have to write it myself...

Finding the raw data

The first challenge is knowing where to find the URL information at all in the DOM. The URL is stored in the location object, which is a property of both window and document. The location object has a few properties, but the one we're interested in today is called search, which returns only the part of the URL starting with the ? character. This returns a string object, which confusingly enough sports a method named search, so you end up writing some redundant-looking code to search the raw query string. Now, there are two main ways you can approach the problem of cracking a query string: on-demand search, or preprocess and store.

Option 1: On-demand search

On-demand searching means to delay processing the query string until a value is actually needed. This approach is preferred when access is needed only rarely. For this approach, you can use a regular expression to parse the string and return the requested value. Since regular expressions are their own topic, I'll gloss over the details of regular expression syntax, but point out the JavaScript-specific parts you'll need to know about. Here's the code:

function queryString( key )
{
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
}

Here, I first define a regular expression that searches for the key delimited by either a ? or & on the left, and = on the right, then capture the right side of the = sign up until the next & or end of line. After the regular expression match is made, the sub-matches are most easily accessed using the global RegExp object; the first 9 sub-matches are stored in the properties $1..$9. In this case, there's only one sub-match possible, so if a match is made, the first sub-match is the one I want.

Option 2: Pre-process and store

Pre-processing is the opposite of on-demand searching; all the processing is done up front whether you will ever use the results or not, and the results are saved for convenient access. This approach is more expensive up-front, but can pay off if the results are accessed frequently. To perform pre-processing, simply include this code in a script block in a page:

location.queryString = new Array();
var pairs = location.search.split( "&" );
for ( i in pairs )
{
    var keyval = pairs[ i ].split( "=" );
    location.queryString[ keyval[0] ] = keyval[1];
}

This approach creates a new expando property of location called queryString, which contains all of the current document's query string key-value pairs as properties.

Option 3: On-demand search & store

Of course, neither of the two options I demonstrated above are completely exclusive of one another; you could write a more complex version that combines the best of both worlds: on-demand searching to spare the expense of values that are never accessed, and storing searched values to spare the expense of repeated accesses to the same values:

var qs = new Array();

function defined( item )
{
    return typeof item != "undefined";
}

function queryString( key )
{
    if ( !defined( qs[ key ] ) )
    {
        var reQS = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
        var offset = location.search.search( reQS );
        qs[ key ] = ( offset >= 0 ) ? RegExp.$1 : null;
    }
    return qs[ key ];
}
Tuesday, July 15, 2008 8:11:56 AM UTC
Here is a blog post describing a function to <strong>parse querystring from url using javascript:
JavaScript QueryString - Parse/Get QueryString with Client-Side JavaScript</strong>
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, i, strike, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview