Safe URL reading and writing (searchparams / queryparams)
The Problem
Query params may have all type of problems
- wrong syntax
- forget to encode
- accidental white spaces
const url = `https://www.google.com/search ` // accidental white space
+ `?q=hello world` // forget to encode whitespace
+ `?oq=hello+world` // wrong syntax (should be '&' instead of '?')
+ `&eq=${encodeURIComponent("hello world")}` // little uglierThe URL constructor
const url = new URL('https://joseavr.com/api/search')
url.searchParams.set('q', text)
url.searchParams.set('model', model)
url.searchParams.set('locale', locale)
url.searchParams.has('page') // true
url.searchParams.get('page') // '1'
url.toString()
// https://joseavr.com/api/search
// ?q=hello+world
// &model=chatgpt-5.1
// &locale=enThis solves:
- Separator characters are corret: & and ? are placed in the right place
- All params are automatically encoded
- No more accidental whitespaces
URL API
URL properties to know:
const url = new URL('https://joseavr.com/notes?page=1#tags');
url.protocol // https:
url.host // joseavr.com
url.pathname // /notes
url.search // ?page=1
url.hash // #tags
url.href // https://joseavr.com/notes?page=1
url.origin // https://joseavr.com
url.searchParams.get('page') // 1Commom functions:
// set query param
url.searchParams.set('page', '1')
// set as key-value pairs
const params = new URLSearchParams({
page: 1,
text: 'foobar',
})
// check if the query exist
url.searchParams.has('page')
// get query param
url.searchParams.get('page')
// get multiple values of same query param (e.g. `&page=1&page=2`)
url.searchParams.getAll('page') // ['1', '2']
// if support mutiple values of same queries
url.serachParams.append("page", "2")
// delete query param
url.searchParams.delete('page')URLSearchParams object
Note that url.searchParams is a URLSearchParams object type
url.searchParams // type URLSearchParams
// if only want to work with query params
const params = new URLSearchParams('page=1')
params.has('page') // true
params.get('page') // '1'