0
0
Node.jsframework~5 mins

URL class for parsing in Node.js

Choose your learning style9 modes available
Introduction

The URL class helps you break down and understand web addresses easily. It makes working with URLs simple and clear.

When you need to get parts like the domain or path from a web address.
When you want to change or add query parameters in a URL.
When you want to check if a URL is valid or well-formed.
When building tools that work with links, like web scrapers or API clients.
Syntax
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.

Examples
This example shows how to get the domain, path, and a query parameter from a URL.
Node.js
const url = new URL('https://example.com/path?name=alice');
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get('name'));
This example changes the path and adds a new query parameter, then prints the full URL.
Node.js
const url = new URL('https://example.com');
url.pathname = '/newpath';
url.searchParams.append('age', '30');
console.log(url.toString());
Sample Program

This program parses a URL, prints parts like host and path, reads a query parameter, adds a new one, and prints the updated URL.

Node.js
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());
OutputSuccess
Important Notes

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.

Summary

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.