Last active
February 20, 2017 22:54
-
-
Save rustedwolf/4a7d2daed0544941305c6074fa0a14ac to your computer and use it in GitHub Desktop.
Parses location.search string in ES2015
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
/* | |
* A method by @tmetler done in ES2015 | |
* Original method source http://www.timetler.com/2013/11/14/location-search-split-one-liner/ | |
*/ | |
/** | |
* Parses location.search string | |
* @return {Obeject} Search parameters | |
*/ | |
function parseSearch() { | |
// Remove the '?' at the start of the string and split out each assignment | |
return location.search.slice(1).split('&') | |
// Split each array item into [key, value] | |
// ignore empty string if search is empty | |
.map(item => { if (item) return item.split('='); }) | |
// Remove undefined in the case the search is empty | |
.filter(x => !!x) | |
// Return the value of the chain operation | |
.reduce((result, [key, val]) => { | |
// Check whenever query contains array values | |
if (key.match(/\[\]$/)) { | |
const realKey = key.substr(0, key.length - 2); | |
let array = result[realKey] || []; | |
array.push(decodeURIComponent(val)); | |
return Object.assign(result, { [realKey] : array }); | |
} else { | |
return Object.assign(result, { [key]: decodeURIComponent(val) }); | |
} | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment