URL
A complete WHATWG-style URL implementation:
new URL(input, base?)
With a base, relative inputs resolve against it:
Properties
Setting a component updates the whole URL:
Methods
Statics
Prefer URL.parse when input is untrusted:
URLSearchParams
Reached through url.searchParams or constructed directly:
Methods
The view is one-way
Edits to the URL re-parse the params — but edits to the params never touch the URL:
Patterns
Build a query safely
Nothing here percent-encodes: set() stores values verbatim,
toString() emits them verbatim, and the URL parser percent-decodes
%XX on the way in (so a decoded & or = silently splits fields —
%26 becomes a field separator, %23 truncates at #). encodeURIComponent
exists — use it, and keep encoded text out of new URL / .search:
Two things that look right but aren't: fetch(urlObject) throws
Invalid URL — always pass a string (fetch(u.href)) — and
u.searchParams.set(...) followed by fetch(u.href) sends the old
query, because param edits never reach the URL.
Parse a request URL
Gotchas
searchParams.sizeandHeaders.sizeare functions — call them (sp.size()), they are not numeric properties.- Query values are never percent-encoded on output — but the URL parser
decodes
%XXon input. Encode withencodeURIComponentand keep encoded strings out ofnew URL/.search. fetch()takes a URL string, not aURLobject (fetch(u)throwsInvalid URL— usefetch(u.href)).for...ofdoesn't work onURLSearchParams(orHeaders) — loop over.entries()instead.URL.parsereturnsnull; the constructor throws. Pick per context.- Input longer than the internal buffer falls back to heap allocation — there is no documented length cap, but absurd URLs are waste.
originis read-only; usehref = …to change the host.- No
URL.canParsein very old environments — it exists here.
See also
fetch— passing URLs tofetch- Request / Response
- Compatibility
