Skip to content

Instantly share code, notes, and snippets.

@steegi
Last active December 14, 2015 20:59
Show Gist options
  • Save steegi/5147716 to your computer and use it in GitHub Desktop.
Save steegi/5147716 to your computer and use it in GitHub Desktop.
Extract the query parameters from a URL using Map/Reduce in JavaScript
/**
* Extracts the query parameters from a URL
* @url {string} url to be analyzed
* @return {string} params object with a property for each named URL query parameter set to the
* value of the parameter.
*/
function getUrlParams(url) {
// Note that a regex should be used to properly split the URL. I.e. an '=' inside a value will be lost
// This function is just to demonstrate the usage of Map/Reduce
var map = url.slice(url.indexOf('?') + 1).split('&').map(function(param) { return param.split('='); });
map.unshift({}); // Insert empty object in the beginning of the array as the start for the reduce operation
return map.reduce(function(params, arg, i){ params[arg[0]] = arg[1]; return params;});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment