Just about every server language out there allows you to work with URL parameters. Surprisingly JavaScript doesn’t have a straight forward way to do this. These methods should help you parse querystring values from the URL.

Simple Approach

If you’d like to keep you jQuery code clean then consider using the $.getQuery method to easily use the url_query() function in your jQuery projects.

// Parse URL Queries Method
(function($){
    $.getQuery = function( query ) {
        query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var expr = "[\\?&]"+query+"=([^&#]*)";
        var regex = new RegExp( expr );
        var results = regex.exec( window.location.href );
        if( results !== null ) {
            return results[1];
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        } else {
            return false;
        }
    };
})(jQuery);

// Document load
$(function(){
    var test_query = $.getQuery('test');
    alert(test_query); // For the URL /?test=yes, the value would be "yes"
});

Advanced Approach

The jQuery URL Parser written by Mark Perkins takes things into more depth, and I recommend it for advanced scenarios where the url_query() function doesn’t quite work.

Here’s an example of how the the URL /ibm-watson/?jennings=done&rutter=done&humanrace=next

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<script type="text/javascript">
$(function(){
    $.url.attr('protocol') // Protocol: "http"
    $.url.attr('path') // host: "www.kevinleary.net"
    $.url.attr('query') // path: "/ibm-watson/"
    $.url.attr('jennings') // query: "done"
    $.url.attr('rutter') // query: "done"
    $.url.attr('humanrace') // query: "next"
});
</script>

Alternative Approach

If all you need is the value of a specific querystring there’s no reason to use jQuery. The following function will allow you to easily work with URL queries in JavaScript.

// Parse URL Queries
function url_query( query ) {
    query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var expr = "[\\?&]"+query+"=([^&#]*)";
    var regex = new RegExp( expr );
    var results = regex.exec( window.location.href );
    if ( results !== null ) {
        return results[1];
    } else {
        return false;
    }
}

// Example usage - /?load=yes
var url_param = url_query('load');
if( url_param ) {
    alert(url_param); // "yes"
}

Have questions? Let me know, I’m happy to help.