Tell me more ×
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, and if not what plugin do you recommend?

share|improve this question
120  
@Ralph - jQuery is a library and not a framework. –  ken Jan 17 '11 at 18:53
5  
I have wrote simple function for retrieving query string parameters without jQuery svlada.com/blog/2012/06/15/how-to-get-url-parameters-javascript –  svlada Jun 25 '12 at 5:37
10  
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables –  Lorenzo Polidori Oct 29 '12 at 14:50
1  
possible duplicate of JavaScript query string –  Cupcake Jul 31 at 23:09
show 4 more comments

58 Answers

We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:

var name = Arg.get("name");

or getting the whole lot:

var params = Arg.all();

and if you care about the difference between ?query=true and #hash=true then you can use the Arg.query() and Arg.hash() methods.

share|improve this answer
add comment

A very lightweight jquery method:

var qs = window.location.search.replace('?','').split('&'),
    request = {};
$.each(qs, function(i,v) {
    var pair = v.split('=');
    return request[pair[0]] = pair[1];
});
console.log(request);

And to alert ,for example ?q

alert(request.q)
share|improve this answer
1  
Neat. There's a few answers in the same vein already - iterating over a split - albeit none using jQuery's each, and I don't think any of them are perfect yet either. I don't understand the return in your closure though, and I think you need to decodeUriComponent the two pair[] values as you read them. –  Rup Apr 2 at 8:48
show 1 more comment

I would rather use split() instead of Regex for this operation:

function getUrlParams() {
    var result = {};
    var params = (window.location.search.split('?')[1] || '').split('&');
    for(var param in params) {
        if (params.hasOwnProperty(param)) {
            paramParts = params[param].split('=');
            result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
        }
    }
    return result;
}
share|improve this answer
add comment

Try this:

String.prototype.getValueByKey = function(k){
    var p = new RegExp('\\b'+k+'\\b','gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};

Then call it like so:

if(location.search != "") location.search.getValueByKey("id");

You can use this for cookies also:

if(navigator.cookieEnabled) document.cookie.getValueByKey("username");

This only works for strings that have "key=value[&|;|$]"... will not work on objects/arrays.

If you don't want to use String.prototype... move it to a function and pass the string as an argument

share|improve this answer
add comment
function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

share|improve this answer
add comment

Here's my own take on this. This first function decodes a URL string into an object of name/value pairs:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

And as an added bonus, if you change some of the args, you can use this second function to put the array of args back into the URL string:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};
share|improve this answer
1  
@greg to create the element in the browser engine, which will parse a url for you and provide search and href methods for interacting with the url string. –  BMitch Apr 18 at 2:15
show 2 more comments

This one works fine

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

taken from here

share|improve this answer
1  
You probably at least want to call decodeUriComponent on the pair[1] before you return it, if not replace pluses with spaces first as in all the other solutions here. Some of the other solutions also prefer a limit of 2 parts on the split = to be more lenient in accepting input. –  Rup May 24 '12 at 8:44
show 2 more comments

The following function returns an object version of your queryString. You can simply write obj.key1 and obj.key2 to access values of key1 and key2 in parameter.

function getQueryStringObject()
{
    var querystring = document.location.search.replace('?','').split( '&' );
    var objQueryString={};
    var key="",val="";
    if(typeof querystring == 'undefined')
    {
        return (typeof querystring);
    }
    for(i=0;i<querystring.length;i++)
    {
        key=querystring[i].split("=")[0];
        val=querystring[i].split("=")[1];
        objQueryString[key] = val;
    }
    return objQueryString;
}

And to use this function you can write

var obj= getQueryStringObject();
alert(obj.key1);
share|improve this answer
add comment

This function converts the querystring to a JSON-like object, it also handles value-less and multi-value parameters:

"use strict";
function getQuerystringData(name) {
    var data = { };
    var parameters = window.location.search.substring(1).split("&");
    for (var i = 0, j = parameters.length; i < j; i++) {
        var parameter = parameters[i].split("=");
        var parameterName = decodeURIComponent(parameter[0]);
        var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
        var dataType = typeof data[parameterName];
        if (dataType === "undefined") {
            data[parameterName] = parameterValue;
        } else if (dataType === "array") {
            data[parameterName].push(parameterValue);
        } else {
            data[parameterName] = [data[parameterName]];
            data[parameterName].push(parameterValue);
        }
    }
    return typeof name === "string" ? data[name] : data;
}

We perform a check for undefined on parameter[1] because decodeURIComponent returns the string "undefined" if the variable is undefined, and that's wrong.

Usage:

"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");
share|improve this answer
add comment

There is a nice little url utility for this with some cool sugaring:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

Check out more examples and download here: https://github.com/websanova/js-url#url

share|improve this answer
add comment

This the most simple and small function JavaScript to get int ans String parameter value from URL

/* THIS FUNCTION IS TO FETCH INT PARAMETER VALUES */

function getParameterint(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=parseInt(url.replace(param+"=",""));
            alert(n); 
}
getParameteraint("page");
getParameteraint("pagee");

/*THIS FUNCTION IS TO FETCH STRING PARAMETER*/
function getParameterstr(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=url.replace(param+"=","");
            alert(n); 
}
getParameterstr("str");

Source And DEMO : http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html

share|improve this answer
1  
I think that can be easily defeated e.g. ?xyz=page&str=Expected&page=123 won't return 123 because it picks up the page string from xyz=page, and str will return Expected&page=123 rather than just Expected if it's not the last value on the line, etc. You're also not decodeUriComponent-ing the values extracted. Plus I couldn't try your demo - I got redirected to a betting website?? –  Rup Jan 25 at 12:23
1  
OK, finally managed to get your demo through adfly. Yes, that works OK but only because you have just the one string parameter and it's last - try using more than one and switching the orders around. Try putting the pagee parameter before the page parameter and it'll fail. For example here's your demo with the order of the three reversed. The other problem is if someone posts a string with a non-ASCII character in it, e.g. a space - it'll get URI encoded and you're not decoding that afterwards. –  Rup Jan 29 at 11:49
show 1 more comment

I believe this to be an accurate and concise way to achieve this (modified from http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}
share|improve this answer
show 2 more comments

If you want array-style parameters URL.js supports arbitrarily nested array-style parameters as well as string indexes (maps). It also handles url-decoding.

url.get("val[0]=zero&val[1]=one&val[2]&val[3]=&val[4]=four&val[5][0]=n1&val[5][1]=n2&val[5][2]=n3&key=val", {array:true});
// Result
{
    val: [
        'zero',
        'one',
        true,
        '',
        'four',
        [ 'n1', 'n2', 'n3' ]
    ]
    key: 'val'
}
share|improve this answer
add comment

This code will create a object which have two method
1. isKeyExist: Check if particular parameter exist;
2. getValue: get value of particular parameter.

 var QSParam = new function() {
        var qsParm = {};
        var query = window.location.search.substring(1);
        var params = query.split('&');
        for (var i = 0; i < params.length; i++) {
            var pos = params[i].indexOf('=');
            if (pos > 0) {
                var key = params[i].substring(0, pos);
                var val = params[i].substring(pos + 1);
                qsParm[key] = val;
            }
        }
        this.isKeyExist = function(query){
            if(qsParm[query]){
                return true;
            }
            else{
               return false;
            }
        };     
        this.getValue = function(query){
            if(qsParm[query])
            {
                return qsParm[query];
            }
            throw "URL does not contain query "+ query;
        }
  };
share|improve this answer
add comment

I did small URL library for my needs here: https://github.com/Mikhus/jsurl

It's more common way of manipulating the URLs in JavaScript, meanwhile it's really lightweight (minified and gzipped < 1KB) and has very simple and clean API. And it does not need any other library to work.

Regarding the initial question, it's very simply to do:

var u = new Url; // current document url
// or
var u = new Url('http://user:[email protected]:8080/some/path?foo=bar&bar=baz#anchor');

// looking for query string params
alert( u.query.bar);
alert( u.query.foo);

// modifying query string params
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']

alert( u.query.foo);
alert( u.query.woo);
alert( u);
share|improve this answer
show 2 more comments
var getUrlParameters = function (name, url) {
    if (!name) {
        return undefined;
    }

    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    url = url || location.search;

    var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];

    while (result = regex.exec(url)) {
        resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
    }

    return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};
share|improve this answer
show 1 more comment

You already got alot of options but I guess if you're going to use node.js then you can simply do this:

var url = require('url');
console.log( url.parse('http://server/program/path/?query=string', true).query );
share|improve this answer
3  
As the question mentions jQuery, I would assume this is in the browser. –  Luca Spiller May 16 at 9:31
add comment

If you do not wish to use a Javascript library you can use the Javascript string functions to parse window.location. Keep this code in an external .js file and you can use it over and over again in different projects.

// Example - window.location = "index.htm?name=bob";

var value = getParameterValue("name");

alert("name = " + value);

function getParameterValue(param)
{
     var url = window.location;
     var parts = url.split('?');
     var params = parts[1].split('&');
     var val = "";

     for ( var i=0; i<params.length; i++)
     {
          var paramNameVal = params[i].split('=');

          if ( paramNameVal[0] == param )
          {
              val = paramNameVal[1];
          }
     }

     return val;
}
share|improve this answer
add comment

I used this code (JavaScript) to get the what is passed through the URL:

function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }

Then to assign the value to a variable, you only have to specify which parameter you want to get, ie if the URL is example.com/?I=1&p=2&f=3

You can do this to get the values:

var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];

then the values would be:

getI = 1, getP = 2 and getF = 3

Thanks, Josh

share|improve this answer
show 1 more comment

There are many solutions to retrieve URI query values, I prefer this one because it's short and works great:

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}
share|improve this answer
show 1 more comment

I took this answer and added support for optionally passing the URL in as a parameter; falls back to window.location.search. Obviously this is useful for getting the query string parameters from URLs that are not the current page:

(function($, undef) {
  $.QueryString = function(url) {
    var pairs, qs = null, index, map = {};
    if(url == undef){
      qs = window.location.search.substr(1);
    }else{
      index = url.indexOf('?');
      if(index == -1) return {};
      qs = url.substring(index+1);
    }
    pairs = qs.split('&');
    if (pairs == "") return {};
    for (var i = 0; i < pairs.length; ++i)
    {
      var p = pairs[i].split('=');
      if(p.length != 2) continue;
      map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return map;
  };
})(jQuery);
share|improve this answer
add comment

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

Not to beat a dead horse, but if you have underscore or lodash, a quick and dirty way to get this done is:

_.object(window.location.search.slice(1).split('&').map(function (val) { return val.split('='); }));
share|improve this answer
show 2 more comments

You should not use regex or jQuery for this.

Use small reusable modules through a package-manager like Bower for things like this, so you can easily reuse code and not having to reinvent the wheel each time.

I've created a tiny module that parses the query string into an object. Use it like this:

// http://sindresorhus.com/?unicorn=cake
var q = queryString.parse(location.search);
//=> {unicorn: 'cake'}
q.unicorn;
//=> 'cake'
share|improve this answer
add comment

protected by Community Oct 23 '11 at 15:27

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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