Course contentsShow
← Web Development
Lesson 939 of 2,98217. URL and History ManagementFree lesson

The URL Constructor

Create and parse URL objects using the URL constructor for safe, structured URL manipulation.

The URL Constructor

You'll learn how to safely create and inspect URL objects using JavaScript's built-in URL constructor.

What Is the URL Constructor?

The URL constructor is JavaScript's native way to create structured URL objects from strings. Instead of manually slicing and concatenating URL strings (which is error-prone), you create a URL object that automatically parses the address into its component parts: protocol, hostname, pathname, search parameters, and more.

Think of it like a mailing address parser — instead of treating "123 Main St, Springfield, IL 62701" as one long string you have to manually cut up, you get an object with separate street, city, state, and zip properties.

Creating URL Objects

// Basic usage
const url = new URL('https://example.com/products?sort=price&page=2');

console.log(url.protocol);  // "https:"
console.log(url.hostname);  // "example.com"
console.log(url.pathname);  // "/products"
console.log(url.search);    // "?sort=price&page=2"

You can also create relative URLs by providing a base URL as the second argument:

const base = 'https://example.com/shop/';
const full = new URL('products/shoes', base);

console.log(full.href);  // "https://example.com/shop/products/shoes"

Why Use URL Constructor?

Manual string manipulation can introduce bugs (missing slashes, improperly encoded characters). The URL constructor handles encoding, validation, and parsing automatically, making your code safer and more readable.

Key Takeaway: The URL constructor parses URL strings into structured objects with automatic validation and encoding, providing a safe alternative to manual string manipulation.