0
0
Node.jsframework~5 mins

Why URL parsing matters in Node.js

Choose your learning style9 modes available
Introduction

URL parsing helps your program understand and work with web addresses easily. It breaks down a URL into parts so you can use or change them.

When you want to get the domain name from a web address.
When you need to read or change query parameters in a URL.
When building a web server that handles different routes.
When validating or cleaning user-entered URLs.
When redirecting users to different pages based on URL parts.
Syntax
Node.js
const url = new URL(inputURL);

// Access parts like url.hostname, url.pathname, url.searchParams
Use the built-in URL class in Node.js to parse URLs easily.
URL parts like hostname, pathname, and searchParams are properties you can read or modify.
Examples
This gets the domain name from the URL.
Node.js
const url = new URL('https://example.com/path?name=alice');
console.log(url.hostname); // example.com
This reads the value of the query parameter 'name'.
Node.js
const url = new URL('https://example.com/path?name=alice');
console.log(url.searchParams.get('name')); // alice
This changes the path part of the URL.
Node.js
const url = new URL('https://example.com/path');
url.pathname = '/newpath';
console.log(url.toString()); // https://example.com/newpath
Sample Program

This program parses a URL, prints parts like host, path, and a query parameter, then changes a query parameter and shows the updated URL.

Node.js
import { URL } from 'url';

const inputURL = 'https://www.example.com/products?category=books&sort=asc';
const url = new URL(inputURL);

console.log('Host:', url.hostname);
console.log('Path:', url.pathname);
console.log('Category:', url.searchParams.get('category'));

// Change the sort order
url.searchParams.set('sort', 'desc');
console.log('Updated URL:', url.toString());
OutputSuccess
Important Notes

Always use the URL class instead of manual string splitting to avoid mistakes.

URL parsing helps keep your code safe and clear when working with web addresses.

Summary

URL parsing breaks a web address into useful parts.

It helps read, change, or validate URLs easily.

Node.js has a built-in URL class to do this simply and safely.