← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 5 of 7

URL module

The URL class breaks a web address into protocol, host, path and more, and builds new ones safely.

In this page:

  1. URL module
Syntax
javascript
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

javascript
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
  1. Parsing URLs with regular expressions
  2. Forgetting a base for relative URLs
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.