Parse the Querystring with jQuery

In a number of the web applications I have recently been working on, I have found it necessary to dissect the URL and access the various parts of the querystring. While the window.location object already has some useful properties, I wanted to be able to reference the indices using bracket or dot notation so I put together this handy plugin for my favorite JavaScript library, jQuery.

Plugin

1
2
3
4
5
6
7
8
9
10
11
12
jQuery.extend({
  parseQuerystring: function(){
    var nvpair = {};
    var qs = window.location.search.replace('?', '');
    var pairs = qs.split('&');
    $.each(pairs, function(i, v){
      var pair = v.split('=');
      nvpair[pair[0]] = pair[1];
    });
    return nvpair;
  }
});

Usage

Assuming the URL is http://mydomain.com/page.html?foo=bar&somevalue=myvalue, you can either access an index directly jQuery.parseQuerystring().foo, or by setting a variable, like this:

var qs = jQuery.parseQuerystring();
//qs['foo'] == "bar"
//qs.somevalue == "myvalue"

The goal of extending the jQuery object with this utility (meaning that it does not require a selected set of elements, and in this case does not even require an argument) was flexibility, however it can easily be converted to a function in the global namespace. If you would rather download the files, they are zipped up and ready (zipParseQuerystring jQuery Plugin).

Are there additional operations you’d like to see added to this, or relating to the URL and querystring? Let me know in the comments.

Update: Code posted to GitHub as a Gist snippet

5 Responses to “Parse the Querystring with jQuery”

  1. ShadowCaster

    Works great, thank you, but I recommend you replace the $ symbol with jQuery for consistency and also so it works when copied into WordPress or the like where the $ variable has not been assigned the jQuery object by default.

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>