Skip to content

Instantly share code, notes, and snippets.

@kares
Created May 5, 2011 11:28
Show Gist options
  • Star 77 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save kares/956897 to your computer and use it in GitHub Desktop.
Save kares/956897 to your computer and use it in GitHub Desktop.
jQuery.parseParams - parse query string paramaters into an object
/**
* $.parseParams - parse query string paramaters into an object.
*/
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
@yairEO
Copy link

yairEO commented Oct 24, 2016

There is a larger debate going on here - http://stackoverflow.com/q/1131630/104380

@Tusko
Copy link

Tusko commented Feb 5, 2018

one line deParams :)

function deParams(str) {
    return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}

@CarabineSK
Copy link

PHPstorm inspection says this part is not quite ideal:
while ( e = re.exec(query) ) {
instead, it is better to use this:
while ((e = re.exec(query)) !== null) {

Same example in mozilla developer page: RegExp.prototype.exec()

@enniosousa
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment