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

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|improve this question
68  
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. –  user2407309 May 30 at 1:12
show 4 more comments

74 Answers 74

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|improve this answer
show 2 more comments

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|improve this answer
show 2 more comments
<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; }
});  

Please check and let me know your comments.

Also Refer : http://jquerybyexample.blogspot.com/2012/05/how-to-get-querystring-value-using.html

share|improve this answer
1  
@Rup : I have got this from codeproject.com/Tips/529496/Handling-QueryString-Using-jQuery –  Pushkraj Jul 23 '13 at 13:14
show 1 more comment

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|improve this answer
add comment

Time for the magic of simplicity...

function getQueryString(URL){
    if (URL.indexOf('?')>=0){
        return = URL.split('?')[1];
    }
}

And if you need to handle #fragment identifiers...

function getQueryAndFragment(URL){
    if (URL.indexOf('?')>=0 || URL.indexOf('#')>=0){
        var result = URL;
        // the #fragment is supposed to be after the ?query
        // but just in case...
        if (URL.indexOf('?') > URL.indexOf('#')){
            result = result.split('#')[1];
        }
        else {
            result = result.split('?')[1];
        }
        return result;
    }
}

Note that given a URL like http://www.domain.com/search?hello#haha these functions will return hello#haha which I am assuming is good behavior, because you will probably want to split up the rest of it for use elsewhere. It would be easy to make it remove the # sign or return only the parts between ? and # (regardless of order), completely without regex.

share|improve this answer
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 at 10:01
add comment

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|improve this answer
add comment

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|improve this answer
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 at 11:54
add comment

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|improve this answer
add comment

This didn't work for me, I want to match `?b' as the 'b' paramter is present, and not match '?return' as the 'r' paramrter, 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|improve this answer
show 2 more comments

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|improve this answer
add comment

Amazing how many overly complicated and incomplete solutions are posted here. Here's what I'm using:

function getUrlParams () {
    var urlParams = {}
    var queryString = window.location.search.split('?')
    if (queryString[1]) {
        var keyValuePairs = queryString[1].split('&')
        for (var i = 0; i < keyValuePairs.length; i++) {
            var keyValuePair = keyValuePairs[i].split('=')
            var paramName = keyValuePair[0]
            var paramValue = keyValuePair[1] ? keyValuePair[1] : ''
            urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
        }
    }
    return urlParams
} // getUrlParams()

Works with following urls:

http://example.com
http://example.com?
http://example.com?test
http://example.com?test=
http://example.com?test=%3F%26%3D
http://example.com?test=ignored&test=%3F%26%3D

Returns an empty string in the first 4 cases, and the string '?&=' in the last two cases. Returning '?&=' rather than 'ignored' in the last case makes it consistent with PHP. Works in IE7.

share|improve this answer
show 1 more comment

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|improve this answer
show 1 more comment
var EmployeeID = getQueryVariable("EmployeesIDs");

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);
        }
share|improve this answer
show 1 more comment
// 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|improve this answer
add comment

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.