Smart Links
Building URLs by string concatenation is fragile and error-prone. Modern JavaScript has a powerful URL object.
The URL Object
const url = new URL('https://api.example.com/search');
url.searchParams.set('q', 'javascript tutorial'); // Handles encoding!
url.searchParams.set('page', '1');
url.searchParams.set('language', 'en');
console.log(url.href);
// https://api.example.com/search?q=javascript+tutorial&page=1&language=en
// Use directly in fetch — no need to call .href
const response = await fetch(url);
Parsing Existing URLs
const url = new URL('https://example.com/path?name=Alice&age=28#section');
console.log(url.hostname); // 'example.com'
console.log(url.pathname); // '/path'
console.log(url.hash); // '#section'
console.log(url.searchParams.get('name')); // 'Alice'
console.log(url.searchParams.get('age')); // '28'
URLSearchParams — Iterate and Manipulate
const params = new URLSearchParams('sort=price&order=asc&page=2');
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}
// sort: price
// order: asc
// page: 2
Tip
Using URLSearchParams automatically encodes special characters (spaces, quotes, &) — protecting you from broken URLs.