Week 43: Use URL() to work with URLs in JavaScript

Using native URL()

In pin-tweet, I manually built the URL by individually encodeURIComponent for each query string.

But discovered native URL() that offers a better way to work with URLs. By default, all params are automatically encoded.

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.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, get on my email list here: subscribe