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

Relative URLs and Base URLs

Resolve relative URLs against a base URL using the second argument of the URL constructor.

Relative URLs and Base URLs

What you'll learn: How to resolve relative URLs against a base URL using the URL constructor's second argument.

The Problem of Relative Paths

When working with URLs, you often encounter relative paths — URLs that don't include the full domain and protocol. For example, /images/photo.jpg or ../docs/guide.html. These are convenient shortcuts, but they need a reference point to make sense.

Think of it like giving directions: "Turn left at the corner" only works if you know where the person is starting from. The starting point is your base URL.

Using the Second Argument

The URL constructor accepts a second argument: a base URL string. When you provide both a relative URL and a base, JavaScript automatically resolves them into a complete, absolute URL:

// Relative URL + Base URL
const base = 'https://example.com/products/';
const relative = '../about/team.html';

const fullURL = new URL(relative, base);
console.log(fullURL.href);
// "https://example.com/about/team.html"

The constructor intelligently handles path navigation like .. (parent directory) and / (root).

Common Use Cases

// Resolve a path from the root
const url1 = new URL('/api/data', 'https://example.com/some/page');
console.log(url1.href); // "https://example.com/api/data"

// Resolve relative to current directory
const url2 = new URL('image.png', 'https://example.com/gallery/');
console.log(url2.href); // "https://example.com/gallery/image.png"

// Going up directories
const url3 = new URL('../../home', 'https://example.com/a/b/c');
console.log(url3.href); // "https://example.com/a/home"

Key Takeaway: Use the second argument of the URL constructor to resolve relative URLs against a base URL, letting the browser handle complex path resolution automatically.