Last active
February 21, 2016 17:24
-
-
Save EldonMcGuinness/6bccc6a0c62f85c378a6 to your computer and use it in GitHub Desktop.
JQuery Querystring Parser
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 ( $ ) { | |
$.qsParameters = function(str) { | |
var qso = {}; | |
var qs = (str || document.location.search) | |
// Check for an empty querystring | |
if (qs == ""){ | |
return qso; | |
} | |
// Normalize the querystring | |
qs = qs.replace(/(^\?)/,'') | |
.replace(/;/g,'&'); | |
while (qs.indexOf("&&") != -1){ | |
qs = qs.replace(/&&/g,'&'); | |
} | |
qs = qs.replace(/([\&]+$)/,''); | |
// Break the querystring into parts | |
qs = qs.split("&"); | |
// Build the querystring object | |
for (var i=0; i < qs.length; i++){ | |
var qi = qs[i].split("="); | |
qi = $.map(qi, function (n) {return decodeURIComponent(n)}); | |
if (qso[qi[0]] != undefined){ | |
// If a key already exists then make this an object | |
if (typeof(qso[qi[0]]) == "string"){ | |
var temp = qso[qi[0]]; | |
if (qi[1] == ""){ | |
qi[1] = null; | |
} | |
//console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]"); | |
qso[qi[0]] = []; | |
qso[qi[0]].push(temp); | |
qso[qi[0]].push(qi[1]); | |
}else if (typeof(qso[qi[0]]) == "object"){ | |
if (qi[1] == ""){ | |
qi[1] = null; | |
} | |
//console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]"); | |
qso[qi[0]].push(qi[1]); | |
} | |
}else{ | |
// If no key exists just set it as a string | |
if (qi[1] == ""){ | |
qi[1] = null; | |
} | |
//console.log("New key: ["+qi[0]+"]["+qi[1]+"]"); | |
qso[qi[0]] = qi[1]; | |
} | |
} | |
return qso; | |
} | |
}( jQuery )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I personally don't see the point of making your code dependent on jQuery. You could just release it as a standalone JS library.
Other than that, good job!