Created
May 22, 2018 02:15
-
-
Save bahdcoder/2d1265dd0c6e804158a914e9bf2bab5e to your computer and use it in GitHub Desktop.
parse and stringify query strings
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
// takes in ?by=kati-frantz and returns { by: 'kati-frantz' } | |
const parse = (queryString) => { | |
if (queryString[0] === '?') { | |
queryString = queryString.substring(1) | |
} | |
let queries = queryString.split("&") | |
const params = {} | |
queries.forEach(query => { | |
const queryObject = query.split('=') | |
params[queryObject[0]] = queryObject[1] | |
}) | |
return params | |
} | |
const removeEmpty = (obj) => { | |
Object.keys(obj).forEach((key) => (obj[key] === null || obj[key] === undefined) && delete obj[key]) | |
return obj | |
} | |
// takes in { by: 'kati-frantz' } and returns ?by=kati-frantz | |
const stringify = (queryObject) => { | |
queryObject = removeEmpty(queryObject) | |
let queryString = '' | |
for (let element of Object.keys(queryObject)) { | |
queryString = `${queryString}&${element}=${queryObject[element]}` | |
} | |
return queryString.substring(1) | |
} | |
module.exports = { | |
stringify, | |
parse | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment