Reading GET variables with JavaScript

by on June 10, 2009


One of the things that isn’t immediately obvious in JavaScript is how to access GET variables. I’ve seen lots of different implementations for this around the web, but the majority of them are bulkier than they need to be. Here’s my favorite way to do it:

<script type="text/javascript">
    function $_GET(q,s) {
        s = s ? s : window.location.search;
        var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
        return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
    }
</script>

What this gives you is a JavaScript implementation of PHP’s $_GET functionality.  I use a regular expression to keep the code to a minimum. Here is a simple example of how to use it:

// this code would print "hello world" if it was at http://localhost/index.php?var1=hello&var2=world
var var1 = $_GET('var1');
var var2 = $_GET('var2');
document.write(var1 + " " + var2);

Another thing I like about this implementation is that it makes it easy to parse GET variables from arbitrary search strings (ex “?var1=hello&var2=world”).  This is handy if you need to access GET variables from an HTML src parameter such as an image or script tag.

// get the src parameter and split it down to the search query string
var src = document.getElementById('example').src;
params = src.split('?');
var var1 = $_GET('var1','?'+params[1]);
Updated 01/14/11 with Kip Robinson’s improvements from the comments