-
-
Save purtuga/5912640 to your computer and use it in GitHub Desktop.
URL param parsing as generated by jQuery.param. Supports both "legacy" style (ex. foo=bar&foo=bar2&bar=foo) as well as new style (ex. foo[]=bar&foo[]=bar2&bar[]=foo). Original fork did not support legacy style where the key had multiple values. When wanting to parse the document's url, remember to only pass in the document.location.search or doc…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(factory){ | |
if (typeof define === "function" && define.amd) { | |
// AMD. Request jQuery and then run the plugin | |
define(factory ); | |
} else { | |
// Global jQuery | |
window.parseParams = factory(); | |
} | |
}(function() { | |
/** | |
* Converts a string that was serialized with jQuery.param back to the object. | |
* | |
* @param {String} str | |
* | |
* @return {Object} | |
* | |
* @example: | |
* | |
* parseParams('foo=bar&foo=bar2&bar=foo'); | |
* | |
* parseParams('foo[]=bar&foo[]=bar2&bar[]=foo'); | |
* | |
*/ | |
var parseParams = function parseParamsFn(str) { | |
var obj = {}, pair, | |
pairs = decodeURIComponent(str).split( "&" ), | |
prevkey, key, prev, newobj, newkey, arg, | |
injectParam = function(key, val) { | |
var firstBracket = key.indexOf('['); | |
if (firstBracket === -1) { | |
if (obj[key] !== undefined) { | |
if (!(obj[key] instanceof Array)) { | |
obj[key] = [ obj[key] ]; | |
} | |
obj[key].push(val); | |
} else { | |
obj[key] = val; | |
} | |
return; | |
} | |
prevkey = key.substring(0, firstBracket); | |
key = key.substr(firstBracket); | |
prev = obj; | |
key.replace(/\[([^\]]+)?\]/g, function(chunk, idx, pos) { | |
var newobj, newkey; | |
if (chunk.match(/\[\d*\]/)) { | |
newobj = prev[prevkey] || []; | |
newkey = idx || '[]'; | |
} else { | |
newobj = prev[prevkey] || {}; | |
newkey = idx; | |
} | |
if (prevkey === '[]') { | |
prev.push(newobj); | |
} else { | |
prev[prevkey] = newobj; | |
} | |
prev = newobj; | |
prevkey = newkey; | |
}); | |
if (prevkey === '[]') { | |
prev.push(val); | |
} else { | |
prev[prevkey] = val; | |
} | |
}; | |
// If not string was passed in, return an empty object | |
if (!str) { | |
return obj; | |
} | |
for( arg = 0; arg < pairs.length; arg++ ) { | |
pair = pairs[ arg ].split( "=" ); | |
injectParam( | |
String(pair[0]).replace(/\+/g, " "), | |
String(pair[1]).replace(/\+/g, " ") | |
); | |
} | |
return obj; | |
}; | |
return parseParams; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment