What you need to know about working with search param APIs
I end up reading documentation on search param APIs every time I need to work with them. This looks like me tabbing back and forth between MDN’s URL and URLSearchParams pages until I find what I’m looking for. After doing this enough times, I’ve realized I could do better. Thus, this post. It includes to the point examples of the usual CRUD actions I need when I’m working with URLs.
Append a search param to the window’s URL (without a force reload)
// https://example.com?foo=1&bar=2
const url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
params.append('baz', '3')
url.search = params.toString()
history.replaceState({}, '', url.toString())
// https://example.com?foo=1&bar=2&baz=3
Get the value of a search param from the window’s URL
// https://example.com?foo=1&bar=2
const params = new URLSearchParams(window.location.search)
const myParam = params.get('foo')
console.log(myParam) // '1'
Update a search param from the window’s URL (without a force reload)
// https://example.com?foo=1&bar=2
const url = new URL(window.location.href)
const urlParams = new URLSearchParams(url.search)
urlParams.set('foo', '9')
url.search = urlParams.toString()
history.replaceState({}, '', url.toString())
// https://example.com?foo=9&bar=2
Remove a search param from the window’s URL (without a force reload)
// https://example.com?foo=1&bar=2
const url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
params.delete('bar')
url.search = params.toString()
history.replaceState({}, '', url.toString())
// https://example.com?foo=1