Skip to content

Instantly share code, notes, and snippets.

@LukeChannings
Created October 16, 2018 15:27
Show Gist options
  • Save LukeChannings/fafc6773be66fd200ab4422a83e3bd97 to your computer and use it in GitHub Desktop.
Save LukeChannings/fafc6773be66fd200ab4422a83e3bd97 to your computer and use it in GitHub Desktop.
queryStringToDict.js
const queryStringToDict = qs => qs
.split('&')
.map(pair => pair.split('=').map(decodeURIComponent))
.reduce((dict, [key, value = true]) => ({ ...dict, [key]: value }), {})
@LukeChannings
Copy link
Author

LukeChannings commented Jan 6, 2024

A more modern version, using newer APIs:

/**
 * queryStringToDict
 * @example `queryStringToDict("foo=bar&baz=abc")` will return `{ foo: "bar", baz: "abc" }`
 * @param {string} queryString a query string, e.g. "foo=bar&baz=abc" (a leading `?` is optional)
 * @returns {Record<string, string>}
 * 
const queryStringToDict = queryString => Object.fromEntries(new URLSearchParams(queryString))

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