Node.js ยท Chapter 15 of 43
URL & Query Strings
The `url` module (and the global `URL` class) helps parse URLs into their parts: protocol, host, pathname, and query string parameters.
Query strings carry extra data in a URL after a `?`, like `?search=node&page=2`, and are commonly used for filtering or pagination.
Parsing URLs
The `URL` class parses a full URL string into properties like `.pathname`, `.searchParams`, and `.hostname`.
Reading query parameters
`url.searchParams.get('key')` retrieves a specific query parameter's value.
Example 1 (javascript)
const { URL } = require('url');
const myUrl = new URL('http://localhost:3000/search?term=node&page=2');
console.log(myUrl.pathname);
console.log(myUrl.searchParams.get('term'));Output
/search
nodeThe URL is parsed into pathname and accessible query parameters.
Example 2 (javascript)
for (const [key, value] of myUrl.searchParams) {
console.log(key, value);
}Output
term node
page 2searchParams is iterable, letting you loop over all query parameters.
Key points
- The URL class parses full URLs into structured parts.
- searchParams.get() reads a specific query parameter.
- Query strings appear after a '?' in a URL.
- searchParams is iterable for looping over all params.
๐ก Note: In Express, query strings are automatically parsed into `req.query`.
