URL and URLSearchParams

Try appending query parameters (?name=clark) or a hash (#heading) to the address bar and see how the demo changes!

URL and URLSearchParams

The URL API provides a standard way to access and modify Uniform Resource Locators through JavaScript. It provides handy properties that decompose a URL into specific segments and surfaces metadata that might not otherwise be easily accessed. You can construct a URL object by passing in a string representing a URL like so:

const url = new URL('https://austincrim.com/blog')
// or
const currentUrl = new URL(window.location)

You then have access to the properties listed above in the demo, plus a few more. This makes working with URLs in your app code much more ergonomic than trying to split on slashes or other string manipulation tactics. URL objects can optionally take a base path parameter that enables interesting things like this:

const basedUrl = new URL('../users/123', 'https://myapp.com/dashboard')

// https://myapp.com/users/123

I have seen some development servers use the URL and base path approach to help load files from a request.

Closely related is the URLSearchParams interface. An instance of URLSearchParams is essentially a key-value store that automatically parses a query string and provides the underlying data. This is really helpful when doing any work with HTML forms and query parameters. Typically, you would construct URLSearchParams from a FormData object or access them through the URL.searchParams attribute on a URL object.

const formData = new FormData(formElement)
const params = new URLSearchParams(formData)

// or

const url = new URL(window.location)
url.searchParams

Then you can interact with the underlying data like this:

const food = url.searchParams.get('favorite-food')
url.searchParams.set('name', 'Fido')

URLSearchParams will automatically handle encoding and decoding for you when getting and setting new values.

Go ahead and try constructing some URLs in the devtools to get familiar with the API and how it might help!

Resources

MDN reference Can I Use?