Created
November 13, 2014 19:44
-
-
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.
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($, 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