Created
February 10, 2012 16:28
-
-
Save wilsonpage/1790639 to your computer and use it in GitHub Desktop.
Snippet to parse a query sting. Returns the string base and key/value object
This file contains 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
/** | |
* Used to transform a query string of params and | |
* values into a useful javascript object. | |
* | |
* @param {String} str | |
* @return {Object} | |
*/ | |
function parseQueryString(str) { | |
var | |
baseName, | |
queryStringIndex, | |
queryString, | |
paramsArray, | |
numParams, | |
paramValArray, | |
result = {}; | |
// get the char index of the '?' | |
queryStringIndex = str.indexOf('?'); | |
// if there is no query string | |
if(queryStringIndex < 0) { | |
return { | |
name: str, | |
params: {} | |
}; | |
} | |
// extract the base string | |
baseName = str.slice(0, queryStringIndex); | |
// trim everything off before the '?' | |
queryString = str.slice(queryStringIndex + 1); | |
// divide each set into an array | |
paramsArray = queryString.split('&'); | |
// get number of params | |
numParams = paramsArray.length; | |
// loop over each param | |
for(var i = 0; i < numParams; i++) { | |
// split into two part param and value array | |
paramValArray = paramsArray[i].split('='); | |
// set the param and value on the result object | |
result[paramValArray[0]] = paramValArray[1]; | |
} | |
// return the final object | |
return { | |
name: baseName, | |
params: result | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment