Created
May 18, 2018 17:16
-
-
Save bahdcoder/9db27d43bf38526d47af508f3ce2d54a 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' } | |
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