Reading GET variables with JavaScript
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:
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:
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.
var src = document.getElementById('example').src;
params = src.split('?');
var var1 = $_GET('var1','?'+params[1]);