Skip to content

Instantly share code, notes, and snippets.

@mrpunkin
Created November 13, 2014 19:44
Show Gist options
  • Select an option

  • Save mrpunkin/dd4322709e865b1c4a0a to your computer and use it in GitHub Desktop.

Select an option

Save mrpunkin/dd4322709e865b1c4a0a to your computer and use it in GitHub Desktop.
My jQuery plugin to parse query strings, including support for arrays and hashes. Also adds String prototype function.
(function($, undef){
$.parseQuery = function(str){
var obj = {};
var soRegex = new RegExp(/\[(\S*)\]$/); // Test against sub objects / arrays
$.each(str.replace(/^\?/, "").split("&"), function(i, param){
param = param.split("=");
var k = decodeURIComponent(param[0]),
v = decodeURIComponent(param[1]);
var m = k.match(soRegex);
if(m){ // hash
var k = k.replace(soRegex, '');
if(m[1].length){ // subkey exists
if(obj[k] === undef) obj[k] = {};
obj[k][m[1]] = v;
}else{ // No subkey, array object
if(obj[k] === undef) obj[k] = [];
obj[k].push(v);
}
} else{
obj[k] = v;
}
});
return obj;
}
String.prototype.parseQuery = function(){ return $.parseQuery(this); };
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment