Learn JavaScript
❯ browser_dom.url_api

URLs with URL & URLSearchParams in JavaScript

$concept

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.

$how it works
1

Parse structurally

new URL("https://a.com:8080/x?y=1#z") exposes every part as properties β€” no splitting, no regex.

2

Manage queries safely

params.set("q", "a b") encodes automatically; toString() serializes β€” hand-encoding bugs eliminated.

3

Resolve relatively

new URL("/next", location.href) joins against a base β€” link resolution without string surgery.

4

Validate before fetching

Construction throws on garbage β€” try/catch (or canParse) gates user-entered URLs.

$example
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);
Output
api.example.com 2
?page=3
1Parsing exposes hostname and the page parameter directly.
2set() updates the query safely encoded β€” no manual & or = handling.
3The serialized ?page=3 is fetch-ready β€” build URLs, don't concatenate them.
$use cases
Parsing current locations and deep-link parameters
Building encoded API query strings safely
Validating user URLs before network use
Relative resolution for portable link handling

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.