Creating and Parsing URLs with the URL Constructor
You'll learn how to safely construct URL objects from strings and extract their individual components like protocol, hostname, and pathname—avoiding fragile string manipulation.
What is the URL Constructor?
The URL constructor creates a structured object from a URL string, automatically parsing it into its constituent parts. Instead of manually splitting strings or using regex, you get a clean API that handles all the edge cases of URL parsing for you.
Think of it like feeding a mailing address into a form that automatically separates the street, city, and ZIP code into labeled fields—the URL constructor does the same for web addresses.
Creating a URL Object
const url = new URL('https://api.example.com:8080/users?page=2#results');
console.log(url.protocol); // "https:"
console.log(url.hostname); // "api.example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/users"
console.log(url.search); // "?page=2"
console.log(url.hash); // "#results"
console.log(url.origin); // "https://api.example.com:8080"
Parsing Relative URLs
You can also parse relative URLs by providing a base:
const base = 'https://example.com/api/';
const relative = new URL('v2/products', base);
console.log(relative.href); // "https://example.com/api/v2/products"
Why This Matters
No more brittle string splitting or regex patterns that break with edge cases. The URL constructor handles encoding, special characters, and malformed inputs predictably. When a URL is invalid, it throws an error you can catch—much cleaner than silent bugs.
Key Takeaway: The URL constructor parses URL strings into structured objects with named properties, making it trivial to read or modify individual components like protocol, hostname, pathname, and more—eliminating error-prone string manipulation.