Created
February 9, 2016 16:26
-
-
Save dan-f/2bcc4d66d149480a0dad to your computer and use it in GitHub Desktop.
Parses a querystring from the URL fragment
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
/** | |
* Converts the querystring portion of the URL into an object | |
* mapping keys to argument values. | |
* | |
* Examples: | |
* - 'foo=bar&baz=quux' -> {foo: 'bar', baz: 'quux'} | |
* - 'foo=bar&' -> {foo: 'bar'} | |
* - 'foo=bar&baz' -> {foo: 'bar', baz: ''} | |
* - 'foo=bar&baz=' -> {foo: 'bar', baz: ''} | |
* | |
* @param queryString {string} | |
* @returns {object} | |
*/ | |
parseQueryString: function (queryString) { | |
return _(decodeURI(queryString).split('&')).map(function (namedVal) { | |
var keyValPair = namedVal.split('='), obj = {}; | |
if ((keyValPair.length === 1 && !keyValPair[0]) || // Empty string | |
keyValPair.length > 2) { // Have something like foo=bar=... | |
throw new Error('Each "&"-separated substring must either be a key or a key-value pair'); | |
} | |
obj[keyValPair[0]] = keyValPair[1]; | |
return obj; | |
}).reduce(function (memo, keyValPair) { | |
return _.extend(memo, keyValPair); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment