Reading URL Properties
What you'll learn: How to extract individual parts of a URL—like protocol, hostname, and pathname—using the properties of a URL object.
Understanding URL Properties
Once you've created a URL object, you can read its individual components through built-in properties. Think of it like dissecting an address: just as "123 Main St, Springfield, IL" has separable parts (street number, street name, city, state), a URL can be broken down into protocol, hostname, pathname, and more.
Available Properties
When you have a URL object, these properties let you access specific pieces:
const url = new URL('https://example.com:8080/products/shoes?size=10&color=blue#reviews');
// Complete URL
console.log(url.href);
// "https://example.com:8080/products/shoes?size=10&color=blue#reviews"
// Protocol (includes colon)
console.log(url.protocol);
// "https:"
// Hostname only
console.log(url.hostname);
// "example.com"
// Path after the domain
console.log(url.pathname);
// "/products/shoes"
// Query string (includes ?)
console.log(url.search);
// "?size=10&color=blue"
// Protocol + hostname + port
console.log(url.origin);
// "https://example.com:8080"
Common Use Cases
These properties are perfect when you need to inspect or log parts of a URL, compare domains, or extract query parameters for further processing. Each property is read-only and always returns a string.
Key Takeaway: URL objects expose individual components like href, origin, protocol, hostname, pathname, and search as convenient properties you can read to understand and work with different parts of a web address.