Grow your CSS skills. Land your dream job.

Last updated on:

Get URL Variables

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

Usage

Example URL:

http://www.example.com/index.php?id=1&image=awesome.jpg

Calling getQueryVariable("id") - would return "1".
Calling getQueryVariable("image") - would return "awesome.jpg".

Comments

  1. kidi
    Permalink to comment#

    Requests = {
    QueryString : function(item){
    var svalue = location.search.match(new RegExp(“[\?\&]” + item + “=([^\&]*)(\&?)”,”i”));
    return svalue ? svalue[1] : svalue;
    }
    }

    //usage
    Requests.QueryString(“id”);

  2. sghakgun
    Permalink to comment#

    nice ! thanks.

  3. Permalink to comment#

    Great work, this is a really nice bit of coding! As always, keep it up!

  4. Nice, really helpful thanks!!

  5. Thanks Chris, totally useful script. Soo going to use that today :D

  6. anup
    Permalink to comment#

    beauty!!!!!!!

  7. Uzair
    Permalink to comment#

    Can i remove the .html extension from my website having a windows based hosting?

    I dont know if the server has Isapi_rewrite installed

    regards

  8. i think that line = return (false) would be create a bug if your url get more than one variable. false can be break a loop and return just first var in your url..

    i think that line should be remove..

    regards,

    nb : pardon me if i wrong :)

    • Patrick McDougle
      Permalink to comment#

      I think you might be mis-reading the brackets. After the for loop has searched all of the vars (name-value pairs) and hasn’t found variable then this function returns false.

  9. Neil
    Permalink to comment#

    Awesome! Thanks very much!

  10. hi my friends sorry if i speak english but i can’t explain in french so
    i got this one in one scripte i created it
    page.html?nom=28/09/1986&from=hossa&too=hisok
    and i want to get the name of variable nom and from and too
    i tried many scripts but they don’t work for me
    please can you tell me how to do it in javascript
    thanks so much

    • Patrick McDougle
      Permalink to comment#

      I think that is what this post is about.

      Just call the function defined above.

      getQueryVariable("nom"); – would return “28/09/1986″.
      getQueryVariable("from"); – would return “hossa”.
      getQueryVariable("too"); – would return “hisok”.

  11. thanks to share :D

  12. Permalink to comment#

    I tested the function of various types and only this worked.
    Congratulations!

  13. I wanted to use this in CoffeeScript if you want to copy and paste this worked for me

    getQueryVariable = (variable) ->
    query = window.location.search.substring(1)

    for el in query.split "&"
                pair = el.split "="
        return pair[1] if pair[0] is variable
    
    return false
    

    tabs is all screwed up

  14. Robert Galindo
    Permalink to comment#

    Added another if statement to check for space characters ‘%20′ in the parameters

    function getQueryVariable(variable) {
    var query = window.location.search.substring(1)
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=")
        if(pair[0] == variable){
            if(pair[1].indexOf('%20')){
                var fullName = pair[1].split('%20')
                return fullName[0] + ' ' + fullName[1]
            }
            else {
                return pair[1];
            }
        }
    }
    return(false)
    

    }

    • Robert Galindo
      Permalink to comment#

      Oops I forgot ‘ != -1 ‘ Sorry about that. Here is the correct code:

      function getQueryVariable(variable) {
      var query = window.location.search.substring(1)
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=")
          if(pair[0] == variable){
              if(pair[1].indexOf('%20') != -1){
                  console.log(pair[1].indexOf('%20'))
                  var fullName = pair[1].split('%20')
                  console.log(fullName)
                  return fullName[0] + ' ' + fullName[1]
              }
              else {
                  return pair[1];
              }
          }
      }
      return(false)
      

      }

  15. Kat
    Permalink to comment#

    does anyone have a link to an actual live form where something like this has been implemented that I could look at as an example? Sorry I am not very experienced with javascript and having a lot of trouble figuring out how to set this up. I think I am doing something really basic wrong but I can’t figure out what.

    • Robert Galindo
      Permalink to comment#

      Hey Kat. I made a Codepen implementing the code above.

  16. Hey Chris,
    URL Decoding the parameters would be necessary if I’m not mistaken.
    Check this solution here: http://stackoverflow.com/a/901144

  17. Howie
    Permalink to comment#

    I am passing a query via the url (http://www.mywebsite.com/appointment-map.aspx?search=33612) and I want to use that query object in the following (urlsearch) and can’t seem to make it work.

  18. kosmos
    Permalink to comment#

    In addition to Robert Galindo’s code:

    function QueryString(variable){
                try{
                    q = location.search.substring(1);
                    v = q.split("&");
                    for( var i = 0; i < v.length; i++ ){
                        p = v[i].split("=");
                        if( p[0] == variable ){
                            if( p[1].indexOf('%20') != -1 ){
                                n = [];
                                for( var j = 0; j < p[1].split('%20').length; j++ ){
                                    n.push(p[1].split('%20')[j]);
                                }
                                str = "";
                                for( var k = 0; k < n.length; k++ ){
                                    str += n[k] + ' ';
                                }
                                return str.trim();
                            }
                            else{
                                return p[1];
                            }
                        }
                    }
                }
                catch (e){
                    console.log(e);
                }
            }
    

    Now we can get more data after the first %20, I mean, all data with spaces, like uri.html?data=more%20than%20one%20space

    I found this info at stackoverflow.com about speeds on “split” and “regex”:

    Split method: 144,780 ±2.17% fastest
    Regex method: 13,891 ±0.85% | 90% slower
    

    Regards.

  19. kosmos
    Permalink to comment#

    Also, as Relfor said, using decodeUriComponent we haven’t to look for spaces (%20) or another symbols (like accents). Less lines of code, better results:

    function QueryString(variable){
            try{
                q = location.search.substring(1);
                v = q.split("&");
                for( var i = 0; i < v.length; i++ ){
                    p = v[i].split("=");
                    if( p[0] == variable ){
                        if( p[1].indexOf('%20') != -1 ){
                            return decodeURIComponent(p[1]);
                        }
                        else{
                            return p[1];
                        }
                    }
                }
            }
            catch (e){
                console.log(e);
            }
        }
    

    Regards.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".