URLs and query strings in JavaScript
The URL class parses; URLSearchParams handles the query.
const url = new URL("https://typestar.io/tours/go?lang=go&tag=a&tag=b#top");
console.log(url.hostname, url.pathname, url.hash);
console.log(url.searchParams.get("lang"), url.searchParams.getAll("tag"));
url.searchParams.set("lang", "rust");
url.searchParams.delete("tag");
url.pathname = "/tours/rust";
console.log(url.toString());
const params = new URLSearchParams({ page: "2", size: "20" });
console.log(params.toString(), Object.fromEntries(params));
console.log(new URL("../basics", "https://typestar.io/tours/go/").pathname);
How it works
- Reading a part is a property, not a regex.
searchParamssupports repeated keys.- Assigning to a part re-serializes the whole URL.
Keywords and builtins used here
Objectconst
The run, in numbers
- Lines
- 13
- Characters to type
- 534
- Tokens
- 136
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 74 seconds.
Step 3 of 3 in Network, step 14 of 18 in Node.js.