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)) ?s=s[1] :s='';
}
</script>
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
</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);
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]);
var src = document.getElementById('example').src;
params = src.split('?');
var var1 = $_GET('var1','?'+params[1]);


Thanks
your code misinterpreted this query:
?a=1&b=2&a=true&c=7xxx
'a' is '1' instead of 'true'
you define 'a' twice. while the regexp could obviously be altered to look for the last instance, it's better coding practice to to avoid ambiguous cases like that.
This is magic, as far as I'm concerned, so I can't diagnose this, but the function only returns the GET variable up to (and not including) the first instance of the letter 'a'. Truly weird!
Does the code work with eg: example.com?a=1#chapter10
Hi
I am trying to understand how this works and wondered why there are two arguments but you only send 1 in example
Ron
Look at the second example I posted. The idea is that you can optionally pass in a search query string.
I am sending this: nats=NjkxNzozODozMg
but when I get back the nats the Mg from the end are missing. And I dont understand why.