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:

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

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
  • James Printer

    Thanks 🙂

  • vsync

    your code misinterpreted this query:

    '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.

  • personAtRandom

    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!

  • Martin

    Does the code work with eg:

    • borr

      no, this will

      function getget(str){
      var ret = Array;
      var pattern = /[&,?]([^=]*)=([^&#]*)/img;
      var _match;

      if(typeof str == 'undefined') var str = window.location;

      while ( _match = pattern.exec(str)){
      if(_match == null) break;
      return ret;

      • Kip

        Actually his code will work, because he is using, not window.location.href. search will be *just* the query string–the hash is already stripped off.

  • Ron

    I am trying to understand how this works and wondered why there are two arguments but you only send 1 in example


    • Look at the second example I posted. The idea is that you can optionally pass in a search query string.

  • monica

    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.

  • hey Josh, your Bio says you like to solve interesting problems, here's one for you

  • Matt

    [^&amp;] doesn't work properly. It defines &amp; as a negated character class… it should be enough to make it just [^&] as that will stop the string at that point.

    Monica that posted before is probably having problems with that… as any result with 'a' 'm' 'p' or ';' will terminate the match.

    • You're absolutely right. Big oops on my part. It should be fixed now.

      • sjaak

        Don't see any fix yet. I'm not really into regular expressions and I see &amp a few times in your code. Could you please publish the right version of it.


        • The remaining &amp's are there on purpose. The published version should work.

          • sjaak

            I had already seen your change, sorry… Stil having a problem; whatever I try, var1 is found and working like a charm, but var2 seems to not be there at all. In other words: the document.write does show var1, but not var2. Looks like there is a problem with your regex for the second get-variable.

          • I take that back. Those &amps; were added by wordpress. They shouldn't be there at all. I've removed them, tested it again and published the fixed version.

            Sorry about that.

  • jack

    thank You, it is what I was looking for.
    good job!

  • kip

    Hi, thanks for the code! I like it, but I noticed two problems:

    1. On the returns, you are returning "s=s[1]" or "s=''". There's no need for the "s=" here–the last line could end with:
    ? s[1] : '';
    2. The result isn't decoded. so if you have "?abc=def%26ghi", and call $_GET('abc'), you're going to get 'def%26ghi', when you probably want 'def&ghi'. (That's what you'd get in PHP too, btw). Instead of returning s[1], you should return decodeURIComponent(s[1])

  • kip

    One other change I'd recommend: differentiate between parameter that is defined but empty string and a parameter that isn't defined at all. To do this you'd have to change the regex and the return line:

    function $_GET(q,s) {
    s = s ? s :;
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
    return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;

    Or to make it a little more verbose, if desired:

    function $_GET(q,s) {
    s = s ? s :;
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
    s = s.replace(/^?/,'&').match(re);
    return typeof s[1] != 'undefined' ? decodeURIComponent(s[1]) : '';

    $_GET('abc', '?abc=123&def=456') => Returns '123'
    $_GET('abc', '?abc=&def=456') => Returns ''
    $_GET('abc', '?abc&def=456') => Returns ''
    $_GET('abc', '?def=456') => In your code, returns ''. With my modification, returns undefined.

    • I like it. Updated my code and added attribution for you as well.

  • Was getting "invalid identifier ?" as an error and it pointed to "s.replace(/^?/,'&')"

    Had to replace the /'s with single quotes, making the line look like:


    After that it worked great!

  • Thanks for this helpful function! One thing I'd like to mention is, that I got the same error message as the FettesPS but when I tried his suggestion of replacing the slashes with single quotes it wasn't working (probably because '^?' indicates it's a string). So I tried to escape the question mark with a backslash and now that the line looks like:

    return (s=s.replace(/^?/,'&')…

    it's working as it should. As I'm a JS newbie I'd like to know why I had to escape the ?, when it was apparently working fine for you (and Kip) without doing so.

    • I think I can answer this myself because it seems like the backslash isn't shown in the comments section (not sure about your initial post). The line of code in my initial comment should read:

      return (s=s.replace(/^BACKSLASH?/,'&')…

      With 'BACKSLASH' being a real backslash.

      • You're a god!!! hehehehe, you found the solution, you escaped the question mark 'cause it is a reserved word of regular expressions!!

  • Alex

    Yep, it doesn't work without escaping the question mark.
    Maybe backslashes are autoremoved from the code section as well

  • tomasz

    Don't you prefer?
    s = s ||;
    s = s ? s :;

  • jerel

    not to lurk, been trying to get this to do anything for hours now. Before i grind my teeth into dust, could someone be so kind as to show any of this working in context?

    say like is the url
    then the page w the script outputs var1 and prints hi?

    I know php well, new to js, getting a tad crazy over here…

  • JRO

    This works better:

    function getQueryVariable(variable) {
    var query =;
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
    return unescape(pair[1]);
    return false;

  • And when have a friendly url htaccess configured?
    I've made a function that get the last variable value. To my current job, works fine.
    But to pass more than one variable value, I'm without time and need at this moment.
    However I've decided leave the functions here for you improve them to reach work fine with multiple vars and arguments into friendly urls.

    //htaccess friendly url: test with "http://localhost/contact-page&quot;. Note: Will get only the last arguments (value).
    function $_HTTP_GET_FREINDLY_URL(lastvalue)
    var lastvalue = window.location.pathname;
    var regxpID = String(lastvalue.match(new RegExp('[a-zA-Z0-9-]+$','g')));

    return regxpID;

    //without htaccess friendly url: test with "http://localhost/?id=contact-page&quot;
    function $_HTTP_GET(variable, value)
    val = (typeof value == null) ? valor = value :;
    var rexp = new RegExp('&'+variable+'(?:=([^&]*))?(?=&|$)','i');
    return (valor = val.replace(/^?/,'&').match(rexp)) ? (typeof val[1] == 'undefined' ? '' : decodeURIComponent(val[1])) : false;

    //Test with this window.alert() Function
    var friendlyURL = ($_HTTP_GET('id') == false) ? $_HTTP_GET_FREINDLY_URL() : $_HTTP_GET('id');



    Have a great weekend!

    • Edit:

      Sorry guys…!

    • 2nd errata:
      return (val = val.replace(/^?/,'&').match(rexp)) ? (typeof val[1] == 'undefined' ? '' : decodeURIComponent(val[1])) : false;

      2nd sorry guys…!!

  • CMH

    The code has some issues. It consistently fails on first run with the regex expression. Good attempt tho.

  • RA2

    I needed to write a script to grab the GET variables  from a URL and after a bit of looking around I didn't see too many examples that would allow me to easily access  the vars by name.  I wrote the following function that for better or worst get's the job done when passed a URL string that contains GET parameters. It doesn't care how many only that they are there.

    function get_url_params(u){
              var theURL = u;
              var JS_GET = new Object();
              var splitURL = theURL.split('?');
                   var splitVars = splitURL[1].split('&');
                   for(i=0; i< splitVars.length; i++){
                        splitPair = splitVars[i].split('=');
                        JS_GET[splitPair[0]] = splitPair[1];
                   }//end for
                   return JS_GET;
              }//end if
                   return false;
         }//end get_url_params

    If also returns false if there are no variables in the url. 

    You could call :
    var testVars = get_url_params(';);
    or any other get parameter name passed to it.