URLs with URL & URLSearchParams in JavaScript
The URL API parses and builds URLs structurally: new URL(str) exposes protocol/host/pathname/search/hash (throwing on invalid input), URLSearchParams manages query strings (get/set/append/delete, iteration, toString), and relative resolution (new URL("/x", base)) handles joins. No more regex-splitting addresses.
Use it for parsing current locations, building API query strings safely (automatic encoding β spaces become %20, never + bugs), and validating user-entered URLs before fetching. URL.canParse statically checks without throwing where supported.
Parse structurally
new URL("https://a.com:8080/x?y=1#z") exposes every part as properties β no splitting, no regex.
Manage queries safely
params.set("q", "a b") encodes automatically; toString() serializes β hand-encoding bugs eliminated.
Resolve relatively
new URL("/next", location.href) joins against a base β link resolution without string surgery.
Validate before fetching
Construction throws on garbage β try/catch (or canParse) gates user-entered URLs.
let u = new URL("https://api.example.com/items?page=2");console.log(u.hostname, u.searchParams.get("page"));u.searchParams.set("page", "3");console.log(u.search);Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.