Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

share

locked by animuson Jul 25 '14 at 19:35

This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here

69  
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables –  Lorenzo Polidori Oct 29 '12 at 14:50
6  
Although the top solution to the question deserves its popularity because of its excellent observation that jQuery is not needed, its method of creating new regular expressions and re-parsing the query string for every parameter desired is extremely inefficient. Far more efficient (and versatile) solutions have been in existence for a long time, for example within this article reprinted here: htmlgoodies.com/beyond/javascript/article.php/11877_3755006_3/… –  Joseph Myers May 14 '13 at 6:00
1  
possible duplicate of JavaScript query string –  Cupcake Jul 31 '13 at 23:09
4  
Joseph, the "excellent observation that jQuery is not needed"? Of course it's not needed. Everything jQuery does, it does using JavaScript. People don't use jQuery because it does stuff that JavaScript can't do. The point of jQuery is convenience. –  Vladimir Kornea May 30 '14 at 1:12

73 Answers 73

this will work.. You need call this function where you need get the parameter by passing its name..

function getParameterByName(name)
{

  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  alert(results[1]);
  if( results == null )
    return "";
  else
    return results[1];
}
share
1  
That's almost identical to the top regexp answer except you're matching the whole URL not just the query string part and you're not removing escapes in the result. –  Rup Jan 22 '14 at 11:54

quick, easy, and fast:

The Function:

    function getUrlVar() {
        var result = {};
        var location = window.location.href.split('#');
        var parts = location[0].replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            result [key] = value;
        });
    return result ;
    }

Usage:

var varRequest = getUrlVar()["theUrlVarName"];
share

Here is String prototype implementation:

String.prototype.getParam = function( str ){
    str = str.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp( "[\\?&]*"+str+"=([^&#]*)" );    
    var results = regex.exec( this );
    if( results == null ){
        return "";
    } else {
        return results[1];
    }
}

Example call:

var status = str.getParam("status")

str can be a query string or url

share

see this post or use this

<script type="text/javascript" language="javascript">
$(document).ready(function()
{
    var urlParams = {};
    (function () 
    {
        var match,
        pl= /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

        while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
    })();

    if( urlParams["q1"] === 1 )
    {
        return 1;
    }
});
</script>
share

I recommend Dar Lessons as a good plugin. I have worked with it fo a long time. You can also use the following code. Jus put var queryObj = {}; before document.ready and put the bellow code in the beginning of document.ready. After this code you can use queryObj["queryObjectName"] for any query object you have

var querystring = location.search.replace('?', '').split('&');
for (var i = 0; i < querystring.length; i++) {
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    queryObj[name] = value;
}
share

This is very simple method to get parameter value(query string)

Use gV(para_name) function to retrieve its value

var a=window.location.search;
a=a.replace(a.charAt(0),""); //Removes '?'
a=a.split("&");

function gV(x){
 for(i=0;i<a.length;i++){
  var b=a[i].substr(0,a[i].indexOf("="));
  if(x==b){
   return a[i].substr(a[i].indexOf("=")+1,a[i].length)}
share

This will parse variables AND arrays from a URL string. It uses neither regex or any external library.

function url2json(url) {
   var obj={};
   function arr_vals(arr){
      if (arr.indexOf(',') > 1){
         var vals = arr.slice(1, -1).split(',');
         var arr = [];
         for (var i = 0; i < vals.length; i++)
            arr[i]=vals[i];
         return arr;
      }
      else
         return arr.slice(1, -1);
   }
   function eval_var(avar){
      if (!avar[1])
          obj[avar[0]] = '';
      else
      if (avar[1].indexOf('[') == 0)
         obj[avar[0]] = arr_vals(avar[1]);
      else
         obj[avar[0]] = avar[1];
   }
   if (url.indexOf('?') > -1){
      var params = url.split('?')[1];
      if(params.indexOf('&') > 2){
         var vars = params.split('&');
         for (var i in vars)
            eval_var(vars[i].split('='));
      }
      else
         eval_var(params.split('='));
   }
   return obj;
}

Example:

var url = "http://www.x.com?luckyNums=[31,21,6]&name=John&favFoods=[pizza]&noVal"
console.log(url2json(url));

Output:

[object]
   noVal: ""
   favFoods: "pizza"
   name:     "John"
   luckyNums:
      0: "31"
      1: "21"
      2: "6"
share

Simple Solution with Plain JS and Regex

alert(getQueryString("p2"));

function getQueryString (Param) {
      return decodeURI("http://www.example.com/?p1=p11&p2=p2222".replace(new RegExp("^(?:.*[&?]" + encodeURI(Param).replace(/[.+*]/g, "$&") + "(?:=([^&]*))?)?.*$", "i"), "$1"));
    }

JsFiddle

share

The shortest possible expression in terms of size to obtain a query object seems to be:

var params = {};
location.search.substr(1).replace(/([^&=]*)=([^&]*)&?/g,
  function () { params[decodeURIComponent(arguments[1])] = decodeURIComponent(arguments[2]); });

You can make use of the A element to parse a URI from a string into its location-like components (to get rid of #..., for example):

var a = document.createElement('a');
a.href = url;
// Parse a.search.substr(1)... as above
share

This didn't work for me, I want to match `?b' as the 'b' parameter is present, and not match '?return' as the 'r' parameter, here is my solution.

window.query_param = function(name) {
  var param_value, params;

  params = location.search.replace(/^\?/, '');
  params = _.map(params.split('&'), function(s) {
    return s.split('=');
  });

  param_value = _.select(params, function(s) {
    return s.first === name;
  })[0];

  if (param_value) {
    return decodeURIComponent(param_value[1] || '');
  } else {
    return null;
  }
};
share

This function will return a parsed JavaScript object with any arbitrarily nested values using recursion as necessary.

Here's a jsfiddle example.

[
  'a=a',
  '&b=a',
  '&b=b',
  '&c[]=a',
  '&c[]=b',
  '&d[a]=a',
  '&d[a]=x',
  '&e[a][]=a',
  '&e[a][]=b',
  '&f[a][b]=a',
  '&f[a][b]=x',
  '&g[a][b][]=a',
  '&g[a][b][]=b',
  '&h=%2B+%25'
].join('');

Given any of the above test examples.

ls = function() {
  var a, b, c, e;
  a = {};
  b = window.location.search.substring(1);
  c = function(d) {
    return d && decodeURIComponent(d.replace(/\+/g, ' '));
  };
  e = function(f, g, h) {
    var i, j, k, l;
    i = g.indexOf('[');
    if (i !== -1) {
      j = g.slice(0, i);
      k = g.slice(1 + i).slice(0, g.slice(1 + i).indexOf(']'));
      l = g.slice(1 + i).slice(1 + g.slice(1 + i).indexOf(']'));
      if (k) {
        if (typeof f[j] !== 'object') {
          f[j] = {};
        }
        f[j][k] = l ? e(f[j], k + l, h) : h;
      } else {
        if (typeof f[j] !== 'object') {
          f[j] = [];
        }
        f[j].push(h);
      }
      return f[j];
    } else {
      if (f.hasOwnProperty(g)) {
        if (typeof f[g] === 'object') {
          f[g].push(h);
        } else {
          f[g] = [].concat.apply([f[g]], [h]);
        }
      } else {
        f[g] = h;
      }
      return f[g];
    }
  };
  b.split('&').forEach(function(m) {
    e(a, c(m.split('=')[0]), c(m.split('=')[1]));
  });
  return a;
};
share
1  
Looks broadly good, but why pre-minify it? It's tricky to follow in places as-is; in particular you're doing a few nasty things around the right-square-bracket line. Also an input something like c[xx=a&c[]=b will crash it. –  Rup Jul 1 '14 at 12:22
// Parse query string
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g,
    m;
while (m = regex.exec(queryString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
share

Doing this reliably is more involved than one may think at first.

  1. location.search, which is used in other answers, is brittle and should be avoided - for example, it returns empty if someone screws up and puts a #fragment identifier before the ?query string.
  2. There are a number of ways URLs get automatically escaped in the browser, which makes decodeURIComponent pretty much mandatory, in my opinion.
  3. Many query strings are generated from user input, which means assumptions about the URL content are very bad. Including very basic things like that each key is unique or even has a value.

To solve this, here is a configurable API with a healthy dose of defensive programming. Note that it can be made half the size if you are willing to hardcode some of the variables, or if the input can never include hasOwnProperty, etc.

Version 1: Returns a data object with names and values for each parameter. It effectively de-duplicates them and always respects the first one found from left-to-right.

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

    var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

    if (!url || typeof url !== 'string') {
        url = location.href; // more robust than location.search, which is flaky
    }
    if (!paramKey || typeof paramKey !== 'string') {
        paramKey = '&';
    }
    if (!pairKey || typeof pairKey !== 'string') {
        pairKey = '=';
    }
    // when you do not explicitly tell the API...
    if (arguments.length < 5) {
        // it will unescape parameter keys and values by default...
        decode = true;
    }

    queryStart = url.indexOf('?');
    if (queryStart >= 0) {
        // grab everything after the very first ? question mark...
        query = url.substring(queryStart + 1);
    } else {
        // assume the input is already parameter data...
        query = url;
    }
    // remove fragment identifiers...
    fragStart = query.indexOf('#');
    if (fragStart >= 0) {
        // remove everything after the first # hash mark...
        query = query.substring(0, fragStart);
    }
    // make sure at this point we have enough material to do something useful...
    if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
        // we no longer need the whole query, so get the parameters...
        query = query.split(paramKey);
        result = {};
        // loop through the parameters...
        for (i = 0, len = query.length; i < len; i = i + 1) {
            pairKeyStart = query[i].indexOf(pairKey);
            if (pairKeyStart >= 0) {
                name = query[i].substring(0, pairKeyStart);
            } else {
                name = query[i];
            }
            // only continue for non-empty names that we have not seen before...
            if (name && !Object.prototype.hasOwnProperty.call(result, name)) {
                if (decode) {
                    // unescape characters with special meaning like ? and #
                    name = decodeURIComponent(name);
                }
                if (pairKeyStart >= 0) {
                    value = query[i].substring(pairKeyStart + 1);
                    if (value) {
                        if (decode) {
                            value = decodeURIComponent(value);
                        }
                    } else {
                        value = missingValue;
                    }
                } else {
                    value = missingValue;
                }
                result[name] = value;
            }
        }
        return result;
    }
}

Version 2: Returns a data map object with two identical length arrays, one for names and one for values, with an index for each parameter. This one supports duplicate names and intentionally does not de-duplicate them, because that is probably why you would want to use this format.

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

   var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

   if (!url || typeof url !== 'string') {
       url = location.href; // more robust than location.search, which is flaky
   }
   if (!paramKey || typeof paramKey !== 'string') {
       paramKey = '&';
   }
   if (!pairKey || typeof pairKey !== 'string') {
       pairKey = '=';
   }
   // when you do not explicitly tell the API...
   if (arguments.length < 5) {
       // it will unescape parameter keys and values by default...
       decode = true;
   }

   queryStart = url.indexOf('?');
   if (queryStart >= 0) {
       // grab everything after the very first ? question mark...
       query = url.substring(queryStart + 1);
   } else {
       // assume the input is already parameter data...
       query = url;
   }
   // remove fragment identifiers...
   fragStart = query.indexOf('#');
   if (fragStart >= 0) {
       // remove everything after the first # hash mark...
       query = query.substring(0, fragStart);
   }
   // make sure at this point we have enough material to do something useful...
   if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
       // we no longer need the whole query, so get the parameters...
       query = query.split(paramKey);
       result = {
           names: [],
           values: []
       };
       // loop through the parameters...
       for (i = 0, len = query.length; i < len; i = i + 1) {
           pairKeyStart = query[i].indexOf(pairKey);
           if (pairKeyStart >= 0) {
               name = query[i].substring(0, pairKeyStart);
           } else {
               name = query[i];
           }
           // only continue for non-empty names...
           if (name) {
               if (decode) {
                   // unescape characters with special meaning like ? and #
                   name = decodeURIComponent(name);
               }
               if (pairKeyStart >= 0) {
                   value = query[i].substring(pairKeyStart + 1);
                   if (value) {
                       if (decode) {
                           value = decodeURIComponent(value);
                       }
                   } else {
                       value = missingValue;
                   }
               } else {
                   value = missingValue;
               }
               result.names.push(name);
               result.values.push(value);
           }
       }
       return result;
   }

}

share
2  
Neat, though the majority of answers here deal with splitting up the query part into parameters rather than extracting it from an arbitrary URL. Most of them assume we're on the current page and so just use location.search to get the string you're extracting. –  Rup Jan 17 '14 at 10:01
1  
I took the very short and vague question to mean something very different than what everyone else did. It's now obvious to me what was meant, and I have updated my answer to include a significantly better design that is on par. –  Seth Holladay Oct 11 '14 at 3:02

protected by Community Oct 23 '11 at 15:27

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.