Use The Platform: URL API
Modern web JavaScript provides an intuitive and feature-rich interface to parse, create and edit URLs info.
This page illustrates only the parts that I use the most; for the full spec, have a look at URL
and URLSearchParams
.
Create a URL
A URL is created by instantiating a new URL instance:
const url = new URL("https://v19i.com");
Manage search params
The created object provides an easy interface to add, edit and remove search params; it behaves similarly to Map
.
Set
url.searchParams.set("key", "value");
url.searchParams.set("valid", false);
url.searchParams.set("email", "test@example.com");
url.searchParams.set("extra", 7);
Delete
url.searchParams.delete("extra");
Update
url.searchParams.set("valid", true");
Get your full address back
href
, toJSON
and toString
will all, with minor differences, return a formatted address.
url.href; // https://v19i.com/?key=value&valid=true&email=test%40example.com
url.toJSON(); // Same as href
url.toString(); // Same as href, but read-only
Interaction with FormData
URLSearchParams
accepts a FormData
instance as constructor argument.
Let’s use this form as an example:
<form>
<div>
<label for="username">Username</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email">
</div>
<input type="submit" value="Update fields">
</form>
FormData
parses a form into a Map
like interface that URLSearchParams
can read and transform to allow easy URL manipulation.
const form = document.querySelector("form");
const data = new FormData(form);
const params = new URLSearchParams(data);
params.toString(); // username=a+username&email=an%40email.com