Last active
January 28, 2020 07:43
-
-
Save crrmacarse/1a385a008acb9b702ee7599f3a2a22ad to your computer and use it in GitHub Desktop.
Custom query string creator and builder!
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
export const getQueryString = string => { | |
const newString = string.trim().replace(/^\?/, '') | |
const splittedAmpersandArr = newString.split('&') | |
let queryStringObj = {} | |
splittedAmpersandArr.forEach(value => { | |
const indexOfEqual = value.indexOf('=') | |
const key = value.slice(0, indexOfEqual) | |
const val = value.slice(indexOfEqual + 1, value.length) | |
const isArr = /[\[\]]{2}$/.test(key) | |
if (key && val) { | |
if (isArr) { | |
const trimmedKey = key.trim().replace(/[\[\]]{2}$/, '') // remove [] at the end | |
if (queryStringObj[trimmedKey]) { | |
queryStringObj[trimmedKey].push(val) | |
} else { | |
queryStringObj[trimmedKey] = [val] | |
} | |
} else { | |
queryStringObj = { [key]: val, ...queryStringObj } | |
} | |
} | |
}) | |
return queryStringObj | |
} | |
export const createQueryString = obj => Object.keys(obj).map(key => { | |
if (Array.isArray(obj[key])) { | |
return obj[key].map(value => `${key}[]=${value}`).join('&') | |
} | |
return `${key}=${obj[key]}` | |
}).join('&') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment