views:

30758

answers:

8

Is there a plugin-less way of retreiving querystring values via jQuery? if so how, and if not what plugin do you recommend?

+11  A: 

If you really don't want to use a plugin, just examine the code and remove the portions you need. I would recommend just using the plugin though.

alex
+2  A: 

omg, so fast...

well, this is the plugin that i use:

http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/

coma
+108  A: 

You don't need jQuery for that purpose you can use the pure JavaScript:

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Artem Barger
+1 I love answers that don't require plugins/libraries
DancesWithBamboo
on the name.replace line you've got a replace that seems to be escaping the \ and ] - is that correct or should it be "\\]" because ] does not need to be escaped?
dan_nl
might be nice to use the jQuery data() function to cache the results for repeated access instead of re-doing the parsing every time...
Ed Woodcock
might be nice, but in this context there is no point do so, since then you will need to handle stale data check and so on...
Artem Barger
its fantastic man!
TheVillageIdiot
Marco Demajo
decode uri component and a + replace are required for this to work properly, edited
Sam Saffron
-1 not enough jquery – [||sumc0da](http://www.doxdesk.com/img/updates/20091116-so-large.gif)
badp
@badp, sorry what? why do I need jquery here?
Artem Barger
@Artem [JQUERY IS REALLY GREAT AND DOES ALL THINGS](http://www.doxdesk.com/img/updates/20091116-so-large.gif) (j/k) (I didn't actually downvote)
badp
Yes, because copy and pasting code like this is totally the solution that should be favored instead of libraries. Hell, why use functions? Just paste the inner-parts of the method around. It's not like we'll ever need to update, maintain, or edit this.
Stefan Kendall
+10  A: 

Roshambo on snipplr.com has a really hott&simple script to achieve this. With his script you also get to pull out just the prams you want easily:

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Here's the gist:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;}

Then just get your parameters from the query string.

So if the url/query string was xyz.com/index.html?lang=de

just call var langval = $.urlParam('lang'); and you've got it

UZBEKJON has a great blog post on this as well:
http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

brandonjp
this is really a simple solution and it works great!
Ajinkya Kulkarni
+53  A: 

I know this was posted almost a year ago, but the suggestions posted here are largely inefficient. The query string will not change at all once the page is loaded, so repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. The other suggestions here also fail to decode the URL correctly.

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

Example querystring:

i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

Result:

urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

Using this code would also allow you to check for presence, e.g. if ("empty" in urlParams) { ... }, so valueless parameters can be used.

This could easily be improved upon to handle array-style query strings too. An example of this is here, but since array-style parameters aren't defined in RFC 3986 I won't pollute this answer with the source code.

Andy E
if you're doing a heavily ajax'd app, then you may be using the hash(#) to "enable the back button"... in that case the querystring would change all the time (see how facebook does it)... though these solutions ignore things that come after the # anways...
Nick Franceschina
@Nick: Anything after the hash resides in the `window.location.hash` property, which is separate from the `window.location.search` property. If the hash changes, it doesn't affect the querystring at all.
Andy E
Thanks! very sleek, easy to use solution.. excellent!
David S
Here's a version that emits them as a table with key/value properties. This is useful in case a key is assigned twice (bad practice, I know, but I had to deal with a lousy back-end.) http://jsbin.com/amage4/edit
jonathanconway
@jonathan: you might have been able to modify my ["php-array-style" example](http://jsbin.com/adali3/2/edit) so that, instead of looking for `[` in the parameter name, it checks if the key already exists. If it does exist, create an array. This would have at least allowed you to still look up sets of values by their name, you would have just had to check if the result was a string or an array of strings.
Andy E
@AndyE that's a really good idea. Here's some code that does it that way: http://gist.github.com/652644.
jonathanconway
@jonathan: great work, and thanks for crediting me :-) btw, you might want to rethink your `isArray` function to something a little more robust: http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array/4029057#4029057
Andy E
+1  A: 
function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 13
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3
Jet
This is an interesting approach, returning an array containing values from the specified parameters. It does have at least one issue - not correctly URL decoding the values, and it would need to URL encode the parameter names used in match too. It will function on simple query strings in its present form though. *ps* don't forget to use the var keyword when declaring variables in *for* statements.
Andy E
+1  A: 

Improved version and removed jQuery dependence (doesn't need regex):

function GetQueryString()
{
    return function(a)
        {
            if (a == "") return {};
            var b = {};
            for (var i = 0; i < a.length; ++i)
            {
                var p=a[i].split('=');
                b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
            }
            return b;
       }(window.location.search.substr(1).split('&'))
}

Given ?a=1&b=2+3

var qs = GetQueryString();
alert("a: " + qs["a"] + "\n" +
    "b: " + qs["b"] + "\n" +
    "c: " + qs["c"]);

Outputs:

a: 1
b: 2 3
c: undefined

Min version:

function GetQueryString(){return function(a){if(a=="")return{};var b={};for(var i=0;i<a.length;++i){var p=a[i].split('=');b[p[0]]=decodeURIComponent(p[1].replace(/\+/g," "))}return b}(window.location.search.substr(1).split('&'))}

There is a ".NET Like" plugin I made.

jQuery.extend
({
    'QueryString': window.location.search.length <= 1 ? new Array() :
        function(a)
        {
            var b = new Array();
            for (var i = 0; i < a.length; ++i)
            {
                var p=a[i].split('=');
                b[p[0]] = unescape(p[1]);
            }
            return b;
       }(window.location.search.substr(1).split('&'))
});

Then you can simply use

var q0 = $.QueryString["search"]; // ?search=123&cat=1 (123)
var q1 = $.QueryString["foo"];    // ?search=123&cat=1 (undefined)

You can just remove the jQuery and turn it into a function...

Min version:

jQuery.extend({'QueryString':window.location.search.length<=1?new Array():function(a){var b=new Array();for(var i=0;i<a.length;++i){var p=a[i].split('=');b[p[0]]=unescape(p[1]);}return b;}(window.location.search.substr(1).split('&'))});
BrunoLM
This is also a nice approach, string splitting instead of using regular expressions. There's a few things worth pointing out, though :-) 1. `unescape` is a deprecated function and is replaced with `decodeURIComponent()`, note that neither of these functions will correctly decode a `+` to a space character. 2. You should declare the result as an object, rather than an array because JavaScript doesn't have associative arrays, per se, and the array you declare is treated as an object by assigning named properties to it anyway.
Andy E
@Andy: 1. I was having problems with IE so I had to change to `unescape`... Always IE... 2. Yea, you're right. I made this a while ago. I think it's time to fix it. :)
BrunoLM
@Andy: I've posted an improved version. What do you think of it?
BrunoLM
@Bruno: nice work... if only I could give you another +1 :-)
Andy E
+4  A: 

Here's my stab at making Andy E's excellent solution into a full fledged jQuery plugin:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);

The syntax is:

var someVar = $.getQueryString('myParam');

Best of both worlds!

Ryan Phelan