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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
URL class in Node.js primarily help you do?Solution
Step 1: Understand the purpose of the URL class
The URL class is designed to parse and handle web addresses, making it easy to access parts like hostname, pathname, and query.Step 2: Compare with other options
Creating servers, encrypting data, and managing file paths are unrelated to URL parsing.Final Answer:
Break down and work with parts of a web address easily -> Option AQuick Check:
URL class = parse web address [OK]
- Confusing URL class with server creation
- Thinking URL class encrypts data
- Mixing URL class with file system modules
https://example.com/path?name=abc in Node.js?Solution
Step 1: Recall the correct syntax for creating a URL object
The URL class requires thenewkeyword and a string argument:new URL(string).Step 2: Check each option
const url = new URL('https://example.com/path?name=abc'); uses correct syntax. const url = URL('https://example.com/path?name=abc'); missesnew. const url = url.parse('https://example.com/path?name=abc'); uses oldurl.parsemethod, not the URL class. const url = new URL.parse('https://example.com/path?name=abc'); incorrectly combinesnewandURL.parse.Final Answer:
const url = new URL('https://example.com/path?name=abc'); -> Option CQuick Check:
Usenew URL()to create URL objects [OK]
- Omitting the 'new' keyword
- Using old url.parse() instead of URL class
- Trying to call URL as a function without 'new'
const url = new URL('https://example.com:8080/path/page?query=123#section');
console.log(url.hostname);
console.log(url.port);
console.log(url.pathname);
console.log(url.hash);Solution
Step 1: Understand URL properties
hostnamegives domain without port,portgives port number,pathnamegives path starting with '/',hashincludes '#' plus fragment.Step 2: Match values from the URL
Hostname is 'example.com', port is '8080', pathname is '/path/page', hash is '#section'.Final Answer:
example.com 8080 /path/page #section -> Option DQuick Check:
URL parts match output A [OK]
- Including port in hostname
- Missing leading slash in pathname
- Omitting '#' in hash
const url = new URL('https://example.com/path');
url.hostname = 'newsite.com';
url.port = 3000;
url.pathname = 'newpath';
console.log(url.href);What is the output?
Solution
Step 1: Understand pathname assignment
Settingurl.pathname = 'newpath'normalizes the path by adding a leading slash, resulting in '/newpath'.Step 2: Construct the full URL
Hostname changes to 'newsite.com', port to '3000', pathname becomes '/newpath'. So full URL is 'https://newsite.com:3000/newpath'.Final Answer:
https://newsite.com:3000/newpath -> Option BQuick Check:
Pathname setter normalizes with leading '/' [OK]
- Expecting '//newpath' without leading slash
- Assuming pathname auto-adds slash
- Confusing pathname with href
id to 42 in this URL: https://shop.com/products?category=books&id=10. Which code correctly updates the URL using the URL class?Solution
Step 1: Identify how to update query parameters
The URL class providessearchParamswith methods likeset()to update query parameters safely.Step 2: Check each option's method
const url = new URL('https://shop.com/products?category=books&id=10'); url.searchParams.set('id', '42'); console.log(url.href); usessearchParams.set(), which is correct. Options A, C, and D use invalid properties or methods not available on URL objects.Final Answer:
const url = new URL('https://shop.com/products?category=books&id=10'); url.searchParams.set('id', '42'); console.log(url.href); -> Option AQuick Check:
Use searchParams.set() to update query [OK]
- Trying to set query directly as object
- Using non-existent methods like setQuery
- Assigning query parameters without searchParams
