Working with URL Module

1. Parsing URLs

Example: WHATWG URL

const u = new URL("https://user:pw@host:8080/p/q?x=1#frag");
console.log(u.protocol, u.hostname, u.pathname, u.search);

2. Getting URL Components

PropertySample
hrefFull URL
originhttps://host:8080
protocolhttps:
host / hostname / portServer
pathnamePath
search / searchParamsQuery
hashFragment
username / passwordCredentials

3. Using URLSearchParams

Example

const p = new URLSearchParams({ a: "1", b: "2" });
p.append("a", "3");
console.log(p.toString()); // a=1&b=2&a=3
for (const [k, v] of p) console.log(k, v);

4. Formatting URLs (url.format)

APIModern Equivalent
url.format(obj)new URL(...).href
url.format(URL, opts)Hide auth/fragment/search options

5. Resolving URLs (url.resolve)

LegacyModern
url.resolve("/a", "b")new URL("b", base).href

6. Encoding URL Components (encodeURIComponent)

FunctionEncodes
encodeURIWhole URL (preserves : / ? # &)
encodeURIComponentSingle component (escapes more)

7. Decoding URL Components (decodeURIComponent)

FunctionUse
decodeURIReverse encodeURI
decodeURIComponentReverse encodeURIComponent

8. Working with URL Hash

Example

const u = new URL("https://x.com/p#section-2");
u.hash = "#section-3";
console.log(u.href);

9. Building URLs Programmatically

Example

const u = new URL("/api/users", "https://example.com");
u.searchParams.set("page", "1");
u.searchParams.set("q", "ada lovelace");
console.log(u.href);

10. Using WHATWG URL API vs Legacy

FeatureWHATWG (modern)Legacy (url.parse)
StandardCross-platformNode-only
Constructornew URL()url.parse() DEPRECATED
Search handlingURLSearchParamsPlain object
Recommendation✅ Use thisAvoid