Skip to content

Instantly share code, notes, and snippets.

@stephenjwatkins
Last active August 8, 2018 20:14
Show Gist options
  • Save stephenjwatkins/e0d29748a023c24c26187be7b7489ee2 to your computer and use it in GitHub Desktop.
Save stephenjwatkins/e0d29748a023c24c26187be7b7489ee2 to your computer and use it in GitHub Desktop.
Utilities for working with search params (without needing to polyfill URLSearchParams).
function getAllSearchParamsFromSearch(search) {
let massagedSearch = search;
if (massagedSearch.charAt(0) === "?") {
massagedSearch = massagedSearch.substring(1);
}
// Filter out the search parameters that have been passed in
return massagedSearch.split("&").map(part => {
return part.split("=");
});
}
function getSearchParamFromSearch(search, param) {
const allSearchParams = getAllSearchParamsFromSearch(search);
const searchParam = allSearchParams.find(([key]) => key === param);
if (searchParam) {
const [, value] = searchParam;
return value;
}
return null;
}
function removeSearchParamsFromSearch(search, paramsToRemove) {
let hasQuestionMark = false;
let massagedSearch = search;
if (massagedSearch.charAt(0) === "?") {
hasQuestionMark = true;
massagedSearch = massagedSearch.substring(1);
}
// Filter out the search parameters that have been passed in
let newParts = massagedSearch.split("&").filter(part => {
const [param] = part.split("=");
return !paramsToRemove.includes(param);
});
let newSearch = newParts.join("&");
if (hasQuestionMark && newSearch.length > 0) {
return `?${newSearch}`;
}
return newSearch;
}
export {
getAllSearchParamsFromSearch,
getSearchParamFromSearch,
removeSearchParamsFromSearch,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment