The URL module allows you to easily parse, construct, and break down web addresses (URLs). When building web servers, you will frequently need to extract specific parts of a URL, such as the path name or query string parameters (like ?user=john&age=25).
The URL module provides an elegant way to dissect these strings without writing messy regular expressions.
Modern JavaScript uses the global URL class to parse strings. Since it is a global API, you do not even need to require it, though the traditional url module still exists.
// Given a standard web address
const myUrl = new URL('https://www.example.com:8080/products/shoes?color=red&size=10#details');
// Break down the URL into its components:
console.log('Host:', myUrl.host); // www.example.com:8080
console.log('Hostname:', myUrl.hostname); // www.example.com
console.log('Port:', myUrl.port); // 8080
console.log('Path:', myUrl.pathname); // /products/shoes
console.log('Search:', myUrl.search); // ?color=red&size=10
console.log('Hash:', myUrl.hash); // #details
The URL class provides a searchParams property, which makes it incredibly simple to read or modify the query parameters attached to the end of a URL.
const myUrl = new URL('https://www.store.com/search?category=electronics&brand=sony');
// Get the value of a specific query parameter
const category = myUrl.searchParams.get('category');
console.log(category); // "electronics"
// Add a new parameter
myUrl.searchParams.append('sort', 'price_desc');
console.log(myUrl.toString());
// "https://www.store.com/search?category=electronics&brand=sony&sort=price_desc"
Which property helps you retrieve the individual query string parameters (like `?id=5`) from a parsed URL?