Created
April 16, 2021 19:54
-
-
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
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
/** | |
* 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