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.
Jump into concepts and practice - no test required
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.
const url = new URL(inputURL); // Access parts like url.hostname, url.pathname, url.searchParams
const url = new URL('https://example.com/path?name=alice');
console.log(url.hostname); // example.comconst url = new URL('https://example.com/path?name=alice'); console.log(url.searchParams.get('name')); // alice
const url = new URL('https://example.com/path'); url.pathname = '/newpath'; console.log(url.toString()); // https://example.com/newpath
This program parses a URL, prints parts like host, path, and a query parameter, then changes a query parameter and shows the updated URL.
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());
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.
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.
const myUrl = new URL('https://example.com:8080/path?search=test#frag');
console.log(myUrl.hostname);
console.log(myUrl.port);
console.log(myUrl.pathname);
console.log(myUrl.search);
console.log(myUrl.hash);const url = new URL('htp://example.com');
console.log(url.hostname);const urlString = 'https://example.com/search?query=nodejs&page=1';