Is there a plugin-less way of retreiving querystring values via jQuery? if so how, and if not what plugin do you recommend?
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.
omg, so fast...
well, this is the plugin that i use:
http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/
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, " "));
}
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
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.
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
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('&'))});
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!