Skip to content

Instantly share code, notes, and snippets.

@csandman
Created April 16, 2021 19:54
Show Gist options
  • Save csandman/1543ec400500d4ca31370313069c1c6a to your computer and use it in GitHub Desktop.
Save csandman/1543ec400500d4ca31370313069c1c6a to your computer and use it in GitHub Desktop.
Utility functions for parsing a query parameter string and stringify-ing a query parameter object
/**
* Stringify an object containing query parameters to be used in a request
*
* @param {object} paramObj An object containing query paramaters
* @returns {string} A string in the format of a query param
*/
export const stringifyQuery = (paramObj) =>
new URLSearchParams(paramObj).toString();
/**
* Parse a string in query string format into an object
*
* @param {string} [paramStr=window.location.search] A string in query parameter format to be parsed. — Default: `window.location.search`
* @returns {object} An object of query parameters
*/
export const parseQuery = (paramStr = window.location.search) =>
[...new URLSearchParams(paramStr).entries()].reduce(
(paramObj, [key, val]) => ({
...paramObj,
[key]: val,
}),
{}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment