Treehouse: 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”);

    • badcrocodile
      Permalink to comment#

      Great snippet, but change the curly quotes to double quotes on this one.

  2. sghakgun
    Permalink to comment#

    nice ! thanks.

  3. Jack
    Permalink to comment#

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

  4. Rene Merino
    Permalink to comment#

    Nice, really helpful thanks!!

  5. Sergei Filippov
    Permalink to comment#

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

    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. elhoussaine
    Permalink to comment#

    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. Thomas Welton
    Permalink to comment#

    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

  12. 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)
      

      }

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

  14. Relfor
    Permalink to comment#

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

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

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

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

  18. Uhelliton Andrade
    Permalink to comment#

    Nice Works! God bless my friend

  19. Thiago Romão Barcala
    Permalink to comment#

    A functional approach (:P):

    function QueryString(variable) {
        return location.search.substring(1).split("&")
            .map(function (p) { return p.split("=") })
            .filter(function (p) { return p[0] == variable })
            .map(function (p) { return decodeURIComponent(p[1]) })
            .pop();
    }
    
  20. Ludovic Urbain
    Permalink to comment#

    Even better, don’t do the work once for each query string parameter.

    function read_query_string(){
        var a=window.location.search.split(/\?/);
        var b=a[1].split("&");
        var c={};
        for(var i=0;i<b.length;i++){
            var d=b[i].split("=");
            c[d[0]]=d[1];
        }
        return c;
    }
    
  21. setiawan
    Permalink to comment#

    How about combain this function with if/else?

    Example:
    U have this url www.domain.com?id=1234&amp;img=test.jpg

    Condition
    If id=xxxx, then do blablabla, else other.

    What script i can use to declare that condition?
    Please help. Thanks…

  22. jayapoorni
    Permalink to comment#

    i need YOUR help for check the last 3 char in the URL.
    EX:
    http://www.google.com
    must check last 3 char that is start from dot(.).
    EX:
    http://www.domainname.xxx
    if wrong last 3 char it should move to any alert msg page. Plz help me

  23. sadashiv
    Permalink to comment#

    can anyone please explain me how to rewrite url using jquery.
    Description:

    i want rewrite the url by removing the folder path from it.
    currently am using asp.net routing which is costly process ,so it would be a great help if any one can give solution for this.

    example: products/cloths/jeans.aspx has to be rewritten as jeans.aspx

    thanks in advance.

  24. Richard

    Implemented the original code and id does return the url variable value if the variable exists, else it returns false. The false returned when the variable does not exist is not a string value but, I assume, a javascript boolean? My question is how can I test for the false return, and then take an action? I want to verify that a selection was made that passes a value in the query string, and if not, give the user a message. Thanks for any help.

  25. Max
    Permalink to comment#

    Hey guys! Great piece of code! Could you tell me how to get current tab url if I am running this code on background page? Any idea if I want to call this code from context menu?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```