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. User Avatar
    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”);

    • User Avatar
      badcrocodile
      Permalink to comment#

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

    • User Avatar
      Dave Land
      Permalink to comment#

      Great, concise snippet. It’s worked where I’ve used it. Knowing the vagaries of data on the Web, there’s bound to be some edge case where it breaks, but so far, this 7½ year old nugget of gold is still serving us well!

  2. User Avatar
    sghakgun
    Permalink to comment#

    nice ! thanks.

  3. User Avatar
    Jack
    Permalink to comment#

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

  4. User Avatar
    Rene Merino
    Permalink to comment#

    Nice, really helpful thanks!!

  5. User Avatar
    Sergei Filippov
    Permalink to comment#

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

  6. User Avatar
    anup
    Permalink to comment#

    beauty!!!!!!!

  7. User Avatar
    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. User Avatar
    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 :)

    • User Avatar
      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. User Avatar
    Neil
    Permalink to comment#

    Awesome! Thanks very much!

  10. User Avatar
    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

    • User Avatar
      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. User Avatar
    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. User Avatar
    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)
    

    }

    • User Avatar
      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. User Avatar
    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.

    • User Avatar
      Robert Galindo
      Permalink to comment#

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

  14. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    Uhelliton Andrade
    Permalink to comment#

    Nice Works! God bless my friend

  19. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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?

  26. User Avatar
    redcom
    Permalink to comment#

    You can get an array of items representing the query params using:

    array = location.search.match(https://cdn.css-tricks.com/\w+(.=)?\w*/gi)

    you can get something like and you can map to an object very easily
    [“app_id”, “123”, “appcode”, “123”]

  27. User Avatar
    Ben
    Permalink to comment#

    This may be a silly question, but I notice the line return (false)

    How is this different from the more usual return false (no brackets)?

  28. User Avatar
    joe
    Permalink to comment#

    good code, but it doesn’t work if you’re looking for first element.

    Calling getQueryVariable(“id”) – should return “1”. But it doesn’t.

    • User Avatar
      joe
      Permalink to comment#

      i should clarify. I modified the function to take a url string.
      function getQueryVariable(url, variable)
      {
      var query = url;
      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);
      }

  29. User Avatar
    Maxime
    Permalink to comment#

    Thanks !!

  30. User Avatar
    Shubham Kumar

    Here’s a simple regex code that I’m using:

    function getQuery(name){
       if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
            return decodeURIComponent(name[1]);
    }
    
    var id = getQuery("id");
    

    Source: http://mycodingtricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

  31. User Avatar
    Hlawu M
    Permalink to comment#

    Great work! but what if I have a query string like in the URL below ?

    Get URL Variables

    This will send “John” instead of the expected “John & James” …. Just a thought.

  32. User Avatar
    Omur
    Permalink to comment#

    Thanks for your helpful post (:

  33. User Avatar
    Kovin
    Permalink to comment#

    What if i want to return default value?

    For example:
    http://www.example.com/index.php?id=1&image=awesome.jpg
    Calling getQueryVariable(“id”) – would return “1”.
    Calling getQueryVariable(“image”) – would return “awesome.jpg”.

    What if:
    http://www.example.com/index.php
    I still want to return “id” value = “predefined value”

  34. User Avatar
    Amber
    Permalink to comment#

    Hi there,

    Could anyone show me exactly how to apply this in html? I have almost no experience with JS. I have tried dozens of iterations and checked many sites and I’m at my wits end.

    My query string at the end of the url is ?foo=jim. I have the JS function inside inside the document head.

    I need ‘jim’ to be inserted as a value of a hidden input field. Below is one of the many iterations I have tried to get this to work.

    <input type="hidden" name="application-id" value=" getQueryVariable('foo')" />.
    

    Can anybody let my know exactly where I’m going wrong here?

    Many thanks,

    Amber

  35. User Avatar
    Jared
    Permalink to comment#

    Hi Amber,
    I have the same problem as you mentioned in this post and I am wondering if you came up with a solution yet?

  36. User Avatar
    Liberator
    Permalink to comment#

    @joe – Just change your line :

    var query = url; </div>
    to :

    var query = url.split('?')[1];

    This will split out the query part of the url.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag