Skip to content

Instantly share code, notes, and snippets.

@figloalds
Created June 27, 2019 11:41
Show Gist options
  • Save figloalds/0a7954cc272cc53d2524f4e028b8ca3e to your computer and use it in GitHub Desktop.
Save figloalds/0a7954cc272cc53d2524f4e028b8ca3e to your computer and use it in GitHub Desktop.
export const queryStringToObject = (url, ignoreObjectsAndArrays) => {
return url.substring(url.indexOf('?')+1)
.split('&')
.reduce(
(a,b)=> {
const kvp = b.split('=')
const frag = {}
const nVal = Number(kvp[1])
frag[kvp[0]] =
(kvp[1] === 'true' || kvp[1] === 'false') ? Boolean(kvp[1]) :
!isNaN(nVal) ? nVal :
kvp[1]
// This code does not handle objects and arrays
// Because there is no clear standard as to
// "how to actually parse objects and arrays from query strings"
// So I'll leave this here: "if value is de-JSON-able then de-JSON it"
if(!ignoreObjectsAndArrays) {
try {
frag[kvp[0]] = JSON.parse(frag[kvp[0]]);
} catch(err) {}
}
//
return Object.assign(a, frag)
},{})
}
// let yourObj = queryStringToObject(yourUrl);
/*
> queryStringToObject('https://duckduckgo.com/?q=query+string+specification&atb=v102-1&ia=web')
returns { q: 'query+string+specification', atb: 'v102-1', ia: 'web' }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment