Skip to content

Instantly share code, notes, and snippets.

@toddmcbrearty
Last active October 27, 2020 21:37
Show Gist options
  • Save toddmcbrearty/7d55d2f2ca46089df3d166e21116fb7d to your computer and use it in GitHub Desktop.
Save toddmcbrearty/7d55d2f2ca46089df3d166e21116fb7d to your computer and use it in GitHub Desktop.
Easily Handle URLSearchParams
/**
* Handles UrL SearchParams
* @param search [search=window.location.href]
* @param key [key=|key=string|key=array]
* @param raw [raw=false]
* @returns {string|object|URLSearchParams}
*/
export const getUrlSearchParams = (
search = window.location.search,
key,
raw = false,
) => {
const urlParams = new URLSearchParams(search);
// see if we are just sending back the raw value of urlParams
if (raw) return urlParams;
// see if we are using `key`
if (key) {
// if the key is an array we want to return all these keys
// if the key doesn't exist it'll send back a null value
if (Array.isArray(key)) {
return getParams(urlParams, key);
}
// send back the single key
return urlParams.get(key);
}
// loop param entries and send that back
return getParams(urlParams);
};
/**
*
* @param urlParams
* @param take [take=null]
* @returns {object}
*/
const getParams = (urlParams, take = null) => {
return Array.from(urlParams.entries()).reduce((carry, item) => {
const [key, value] = item;
//if we have a take and if the key is not in the [take array|equal to key] return the key
if (take && Array.isArray(take) && !take.includes(key)) {
return carry;
}
return {
...carry,
[key]: value,
};
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment