Skip to content

Instantly share code, notes, and snippets.

@bahdcoder
Created May 22, 2018 02:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahdcoder/2d1265dd0c6e804158a914e9bf2bab5e to your computer and use it in GitHub Desktop.
Save bahdcoder/2d1265dd0c6e804158a914e9bf2bab5e to your computer and use it in GitHub Desktop.
parse and stringify query strings
// 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