The URL class helps you break down and understand web addresses easily. It makes working with URLs simple and clear.
URL class for parsing in Node.js
const myUrl = new URL(inputString); // Access parts like myUrl.hostname, myUrl.pathname, myUrl.searchParams
The inputString must be a full URL including the protocol (like https://).
You can use myUrl.searchParams to easily work with query parameters.
const url = new URL('https://example.com/path?name=alice'); console.log(url.hostname); console.log(url.pathname); console.log(url.searchParams.get('name'));
const url = new URL('https://example.com'); url.pathname = '/newpath'; url.searchParams.append('age', '30'); console.log(url.toString());
This program parses a URL, prints parts like host and path, reads a query parameter, adds a new one, and prints the updated URL.
import { URL } from 'url'; const myUrl = new URL('https://www.example.com/products?category=books&sort=asc'); console.log('Host:', myUrl.host); console.log('Pathname:', myUrl.pathname); console.log('Category:', myUrl.searchParams.get('category')); // Add a new query parameter myUrl.searchParams.append('page', '2'); console.log('Updated URL:', myUrl.toString());
Always include the protocol (like http:// or https://) when creating a new URL object.
The searchParams property is very useful for adding, deleting, or getting query parameters easily.
If the input string is not a valid URL, the constructor will throw an error, so handle exceptions if needed.
The URL class breaks down web addresses into easy parts.
You can read and change parts like the domain, path, and query parameters.
It helps you work safely and clearly with URLs in your Node.js programs.