Skip to content

Instantly share code, notes, and snippets.

@rustedwolf
Last active February 20, 2017 22:54
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 rustedwolf/4a7d2daed0544941305c6074fa0a14ac to your computer and use it in GitHub Desktop.
Save rustedwolf/4a7d2daed0544941305c6074fa0a14ac to your computer and use it in GitHub Desktop.
Parses location.search string in ES2015
/*
* 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