Last active
December 14, 2015 20:59
-
-
Save steegi/5147716 to your computer and use it in GitHub Desktop.
Extract the query parameters from a URL using Map/Reduce in JavaScript
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
/** | |
* 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