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
| Property | Sample |
|---|---|
href | Full URL |
origin | https://host:8080 |
protocol | https: |
host / hostname / port | Server |
pathname | Path |
search / searchParams | Query |
hash | Fragment |
username / password | Credentials |
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)
| API | Modern Equivalent |
|---|---|
url.format(obj) | new URL(...).href |
url.format(URL, opts) | Hide auth/fragment/search options |
5. Resolving URLs (url.resolve)
| Legacy | Modern |
|---|---|
url.resolve("/a", "b") | new URL("b", base).href |
6. Encoding URL Components (encodeURIComponent)
| Function | Encodes |
|---|---|
encodeURI | Whole URL (preserves : / ? # &) |
encodeURIComponent | Single component (escapes more) |
7. Decoding URL Components (decodeURIComponent)
| Function | Use |
|---|---|
decodeURI | Reverse encodeURI |
decodeURIComponent | Reverse encodeURIComponent |
8. Working with URL Hash
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
| Feature | WHATWG (modern) | Legacy (url.parse) |
|---|---|---|
| Standard | Cross-platform | Node-only |
| Constructor | new URL() | url.parse() DEPRECATED |
| Search handling | URLSearchParams | Plain object |
| Recommendation | ✅ Use this | Avoid |