import { URL } from 'url'; const myUrl = new URL('https://example.com:8080/path/page?name=chatgpt&lang=en#section1'); console.log(myUrl.hostname); console.log(myUrl.port); console.log(myUrl.pathname); console.log(myUrl.searchParams.get('name')); console.log(myUrl.hash);
The hostname is the domain without protocol or port. The port is "8080" as specified. The pathname includes the leading slash. The searchParams.get('name') returns the value of the 'name' query parameter. The hash includes the leading '#'.
import { URL } from 'url'; const url = new URL('https://example.com/search?query=nodejs');
append adds a new parameter preserving existing ones. set replaces the parameter if it exists or adds it if not. Options C and D overwrite the entire query string, removing existing parameters.
Option A is missing the scheme before '://', which is required. This causes a TypeError. Other options have valid URL formats.
import { URL } from 'url'; const url = new URL('https://example.com'); url.searchParams.get('page').toUpperCase();
The get method returns null if the parameter is missing. Calling toUpperCase() on null causes a TypeError.
url.origin?import { URL } from 'url'; const url = new URL('https://user:pass@example.com:8443/path?query=1#frag');
The origin property returns the scheme, hostname, and port. It does not include username or password.