Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active August 17, 2018 19:24
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 nathansmith/04eeb43e161746a95bb65a32ef572410 to your computer and use it in GitHub Desktop.
Save nathansmith/04eeb43e161746a95bb65a32ef572410 to your computer and use it in GitHub Desktop.
This method splits apart a query string and converts it into an regular object.
/*
This method splits apart a
query string and converts
it into an regular object.
*/
const querySplitter = (url = '') => {
// Split apart.
const parts = url.split('?')
const query = parts[1] || parts[0]
const pairs = (query || '').split('&')
// Set in conditional.
const o = {}
// Loop through.
for (const pair of pairs) {
// Split apart.
const arr = pair.split('=')
const key = arr[0]
const val = arr[1]
// Add to object?
if (key && val) {
o[key] = val
}
}
// Expose object.
return o
}
// Used like this.
console.log(
querySplitter('https://example.com/index.html?query=1&foo=2&bar=3')
)
// Or, used like this.
console.log(
querySplitter('query=1&foo=2&bar=3')
)
// Yields empty object.
console.log(
querySplitter('')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment