Last active
August 17, 2018 19:24
-
-
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 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
/* | |
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