Skip to content

Instantly share code, notes, and snippets.

@wilsonpage
Created February 10, 2012 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilsonpage/1790639 to your computer and use it in GitHub Desktop.
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
/**
* 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