Last active
December 15, 2015 21:39
-
-
Save westonwatson/5326795 to your computer and use it in GitHub Desktop.
parse a(n) URI and return an object with the Key Value pairs. Original Code from the Answer here: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter. Check the history for any modifications or compare to the original in the before mentioned Question URL.
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
//I refactored this to except a parameter, as I would like to parse many URI Queries | |
function parseQueryString(query) { | |
//let's use an object, arrays aren't always the best for Key Value Pairs IMHO | |
var query_string = {}; | |
//original code didn't take in params. | |
//use "window.location.search.substring(1)" to get the current URI request. | |
//this splits each Key Value pair by the "&" seperator | |
var vars = query.split("&"); | |
//loop through Key Value Pair strings from the previous split | |
for (var i=0;i<vars.length;i++) { | |
var pair = vars[i].split("="); | |
// If first entry with this name | |
if (typeof query_string[pair[0]] === "undefined") { | |
query_string[pair[0]] = pair[1]; | |
// If second entry with this name | |
} else if (typeof query_string[pair[0]] === "string") { | |
var arr = [ query_string[pair[0]], pair[1] ]; | |
query_string[pair[0]] = arr; | |
// If third or later entry with this name | |
} else { | |
query_string[pair[0]].push(pair[1]); | |
} | |
} | |
return query_string; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
refactored to accept a query string parameter (instead of only looking at the current URI/query) and added some light commentary :)