Skip to content

Instantly share code, notes, and snippets.

@yurkimus
Last active September 2, 2023 14:28
Show Gist options
  • Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Building URL with filtered URLSearchParameters
const url = createUrl.bind(null, 'https://jsonplaceholder.typicode.com')
const todosUrl = url('todos', { _limit: 10, _offset: undefined, id: null })
todosUrl.toString() // => 'https://jsonplaceholder.typicode.com/todos?_limit=10'
/**
* Clears unwanted search parameters (null, undefined, or empty string) from a given URLSearchParams object.
*
* @param {URLSearchParams} searchParams - The URLSearchParams object to be cleared.
*
* @returns {URLSearchParams} - The cleared URLSearchParams object.
*/
const clearSearchParams = searchParams => {
Array.from(searchParams)
.filter(
([, value]) => value === '' || value === 'null' || value === 'undefined'
)
.forEach(([key]) => searchParams.delete(key))
return searchParams
}
/**
* Constructs a URL by combining pathname, search parameters, and base URL, while clearing unwanted search parameters.
*
* @param {string} pathname - The path portion of the URL.
* @param {ConstructorParameters<typeof URLSearchParams>[0]} searchParamsInit - An object containing the search parameters.
* @param {string} base - The base URL to be combined with pathname and search parameters.
*
* @returns {URL} - The constructed URL object.
*/
const createUrl = (base, pathname, searchParamsInit) => {
const created = new URL(pathname, base)
const searchParams = new URLSearchParams(searchParamsInit)
created.search = clearSearchParams(searchParams).toString()
return created
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment