URL module
The URL class breaks a web address into protocol, host, path and more, and builds new ones safely.
In this page:
Syntax
const url = new URL(text, base);
url.protocol
url.hostname
url.pathname
url.searchParams
URL module
new URL(text, base) parses and validates addresses. It exposes protocol, hostname, port, pathname, search and hash. Setting properties rebuilds the address correctly with encoding.
Note:
An invalid URL throws a TypeError, so wrap untrusted input in try/catch.
Example: URL module
const u = new URL("https://[email protected]:8080/a/b?x=1#top");
console.log(u.protocol, u.hostname, u.port);
console.log(u.pathname, u.search, u.hash);
u.searchParams.set("y", "two words");
console.log(u.href);
try { new URL("not a url"); } catch (e) { console.log(e.name); }
// Output:
// https: example.com 8080
// /a/b ?x=1 #top
// https://[email protected]:8080/a/b?x=1&y=two+words#top
// TypeError
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Parsing URLs with regular expressions
- Forgetting a base for relative URLs
- Not catching invalid URLs
Chapter Summary
- URL parses addresses
- Exposes pathname, search, hash
- Relative URLs need a base
- Invalid input throws
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: