Skip to content

Instantly share code, notes, and snippets.

@pirate
Last active December 15, 2023 07:17
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save pirate/9298155edda679510723 to your computer and use it in GitHub Desktop.
Save pirate/9298155edda679510723 to your computer and use it in GitHub Desktop.
Parse URL query parameters in ES6
function getUrlParams(search) {
const hashes = search.slice(search.indexOf('?') + 1).split('&')
const params = {}
hashes.map(hash => {
const [key, val] = hash.split('=')
params[key] = decodeURIComponent(val)
})
return params
}
console.log(getUrlParams(window.location.search))
@eyecatchup
Copy link

eyecatchup commented Apr 24, 2020

Unfortunately even the native URLSearchParams implementation doesn't handle array query parameters. :(

So, here's another take on array query parameters. Tested on

https://gist.github.com/pirate/9298155edda679510723?abc=foo&def=[asf]&xyz==5&flag&&double&q=test1=test2&keyB=hff92hfgg=&arr[]=ArrayValue1&arr[]=ArrayValue2&arr[]=ArrayValue3&arr2[0]=ArrayValue1&arr2[1]=ArrayValue2&arr2[2]=ArrayValue3&fields=kind,items(title,characteristics/length)
const getQueryParams = () => {
    let params = {};
    (new URLSearchParams(document.location.search)).forEach((d, e) => {
      let a = decodeURIComponent(e), c = decodeURIComponent(d)
      if (a.endsWith("[]")) {
        a = a.replace("[]", ""), params[a] || (params[a] = []), params[a].push(c)
      } else {
        let b = a.match(/\[([a-z0-9_\/\s,.-])+\]$/g)
        b ? (a = a.replace(b, ""), b = b[0].replace("[", "").replace("]", ""), params[a] || (params[a] = []), params[a][b] = c) : params[a] = c
      }
    })
    return params
}

@marcodpt
Copy link

marcodpt commented May 9, 2021

I create an alternative project if you want to use es6 module, with a very simple api:
query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment