Use Javascript to Parse a Query String

Most server-side scripting languages, like PHP, come with built-in functionality for reading query strings. Javascript doesn’t have any kind of standard counterpart, but that doesn’t mean you can’t use query strings in Javascript.

With some String functions, you can create your own function to parse a query string attached to the request url and store it in an associative array – just like PHP would for you.

What Are Query Strings For

If you’re developing anything more than a basic informative page, you’ll need to pass information from one page to the next. You might want to pass a search query, some form values, the answer to a quiz question, or any number of other things. Passing this information is the first step in converting your page from a static bit of information into a dynamic application.

One way to pass information between pages is to use a query string. That’s the long line of text after the ‘?’ in a URL. Kind of like this.

http://www.google.com/search?hl=en&q=widgets&btnG=Google+Search

That’s a standard query string attached to a Google search. It sends a few values to the new page – hl (en), q (widgets), and btn (Google Search). These values are then used to determine what is displayed on the new page.

In PHP, these values are automatically stored in an associative array – the $_GET array. To make these values easily available to our Javascript code, we can write a function to do the same thing.

The Structure of a Query String

In order to break a query string down, we need to understand the rules for building one.

A query string always starts with ‘?’. This separates the query string from the actual URL.

This is followed by key-value pairs, like “key=value”. If there is more than one key-value pair, they are separated by an ampersand – “key1=value1&key2=value2″.

Finally, these values are url_encoded. Special characters – like spaces, ampersands, and equal signs – are converted to code so that they don’t interfere with the URL or the query string.

Step One: Get the Request String and Separate the Query

The first thing we need to do is get the entire request string and separate out just the query string.

//  Fetch the entire request string
var href = new String(window.location.href);
var hrefParts = href.split('?');
 
//  [0] is the URL, [1] is the query string
var query = new String(hrefParts[1]);

The request string is accessible through the window.location object. We use the split method of the string class to explode it at the ‘?’. This leaves us with two parts, and we save the entire query string in the variable query.

Step Two: Get the Key Value Pairs

At this point, our query string in the variable query might look something like this:

hl=en&q=widgets&btnG=Google+Search

To get the key-value pairs, we can use another split() call. This time, we split the string at each ampersand (&). The resulting array will contain the strings “hl=en”, “q=widgets”, and “btnG=Google+Search”.

var valuePairs = query.split('&');

Step Three: Loop Through and Create an Array

Now we can loop through the array valuePairs, split each pair, and create a new array where each value is indexed by its key. This gives us a nicely indexed array just like PHP would.

var getArray = new Array();
 
for each (var pair in valuePairs) {
  // [0] = key, [1] = value
  var tempPair = pair.split('=');
 
  // Unescape converts the text back from URL encoding
  getArray[tempPair[0]] = unescape(tempPair[1]);
}

At this point, getArray[] should hold all of the values in our query string.

Why Bother?

Good question. If PHP (and other server side scripts) automatically parse query strings, why should we bother using Javascript for it?

One reason may be to use query strings to pass information on pages that don’t have any server side scripting enabled. I was looking into a web design competition for high school students, and it doesn’t allow any server-side scripts – only HTML, CSS, and Javascript.

With this method, we could use query strings to bring a little dynamism to the party.

This is also helpful for reading query strings in general – not just the one in the request string. For example, if you use Ajax to get a value from a php script, how is the output formatted?

It may be plain text if it’s just one variable, or it may be in an XML format. If the output is just a handful of key-value pairs, it might be easier and more efficient to create a query string and parse it with this function.

Or… maybe it’s just fun to say “I can do this.” That’s a good enough reason for me.

And as usual, here’s the full function, in case you had some trouble.

function parseQueryString(fullHref) {
  var hrefParts = fullHref.split('?');
 
  //  [0] is the URL, [1] is the query string
  var query = new String(hrefParts[1]);
 
  var valuePairs = query.split('&');
  var getArray = new Array();
 
  for each (var pair in valuePairs) {
    // [0] = key, [1] = value
    var tempPair = pair.split('=');
 
    // Unescape converts the text back from URL encoding
    getArray[tempPair[0]] = unescape(tempPair[1]);
  }
  return getArray;
}
 
//  To use it, pass the request string or another href
//  to the function.  It returns the array.
var href = new String(window.location.href);
var getArray = parseQueryString(href);
Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , ,

5 Comments to “Use Javascript to Parse a Query String”

  1. Alex said this on

    I get JS errors when running this code exactly as is. The error seems to be with the for-each loop.

    the error:
    Expected’(‘

    char 6 of this line:
    for each (var pair in valuePairs) {

    what is missing from your code that is causing this error?

  2. Adila said this on

    I guess it’s the :
    for each (var pair in valuePairs)

    that trigger it
    “for each”

  3. Jess said this on

    there’s no for each loop in javascript….anybody knows the equivalent for collection?

  4. Christian said this on

    I just hoping you could give me some advice…right now I have a page where I can enter a URL in a text box and using a command button, decode it. Here is how the function looks:

    function decode() {
    var obj = document.getElementById(‘dencoder’);
    var encoded = obj.value;
    obj.value = unescape(encoded.replace(/\+/g, ” “));
    }

    Can you help me combine the two so when I press the button it parses out the URL as well

  5. Links Necklaces said this on

    These are typically my favored items simply because they’re thus versatile. Why reduce yourself with your customer to male it which could only always be worn together with silver or simply only with gold? These can be tasteful and also elegant and can contribute to a lot of beautiful types.

Leave a Reply