Skip to content

Instantly share code, notes, and snippets.

@bahdcoder
Created May 18, 2018 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahdcoder/9db27d43bf38526d47af508f3ce2d54a to your computer and use it in GitHub Desktop.
Save bahdcoder/9db27d43bf38526d47af508f3ce2d54a to your computer and use it in GitHub Desktop.
parse-and-stringify-query-strings
// takes in ?by=kati-frantz and returns { by: 'kati-frantz' }
export 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
export const stringify = (queryObject) => {
queryObject = removeEmpty(queryObject)
let queryString = ''
for (let element of Object.keys(queryObject)) {
queryString = `${queryString}&${element}=${queryObject[element]}`
}
return queryString.substring(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment