In pin-tweet, I manually built the URL by individually encodeURIComponent
for each query string.
Ref: pinboard-service.js
But discovered native URL() that offers a better way to work with URLs. By default, all params are automatically encoded.
searchParams.set()
- for building the URLsearchParams.get()
- for parsing the URLsearchParams.has()
- to check for the existence of a param
You can check searchParams
for other
helpful functions.
const url = new URL('http://example.org')
url.searchParams.set('q', 'demo')
url.searchParams.set('title','some long title')
url.searchParams.set('third_param', 3)
url.searchParams.set('boolean_param', true)
url.searchParams.set('invalid_param', 'some value')
const destinationURL = url.toString() // http://example.org/?q=demo&title=some+long+title
// fetching and checking keys
url.searchParams.has('page') // false
url.searchParams.get('third_param') // '3'
url.toString() // http://example.org/?q=demo&title=some+long+title&third_param=3&boolean_param=true&invalid_param=some+value
if (url.searchParams.has('invalid_param')) {
url.searchParams.delete(key)
}
url.searchParams.size // 4
url.toString() // http://example.org/?q=demo&title=some+long+title&third_param=3&boolean_param=true
I made pin-tweet to use URL() via tech: using native URL() for setting the URL #20 PR.
For my new posts, Subscribe via weekly RSS, common RSS or Subscribe via Email