Summary - URL and query string
- Node.js course
- Intermediate
- Lesson 111/116
- 5 min
Combine URL, URLSearchParams and querystring to write a URL parser.
Summary - URL and query string
In this group you learned Node.js's URL tools: parsing with new URL(), query management with URLSearchParams, properties like pathname/hostname, relative resolution with new URL(relative, base), and the querystring module. Now we will combine them in a URL parser.
Structure: parse a URL with new URL(), turn its query into an object with querystring.parse, print hostname and query values on separate lines. This is the foundational step of a real web scraper or API client: you first parse the address, then take the query parameters. The output is deterministic because the address and query are fixed.
Practice Write a URL parser
Create a URL with const url = new URL("https://example.com:8080/path?q=merhaba&s=1");. Import with const querystring = require("node:querystring");. Parse the query with const parsed = querystring.parse(url.search.slice(1)); (skip the ? with slice(1)). Print with console.log(url.hostname), console.log(parsed.q) and console.log(parsed.s).
Starter code
// Create a URL
// write here
// Import the querystring module
// write here
// Parse the query (skip the ? mark)
// write here
// Print hostname, q and s values
// write hereSample solution
const url = new URL("https://example.com:8080/path?q=merhaba&s=1");
const querystring = require("node:querystring");
const parsed = querystring.parse(url.search.slice(1));
console.log(url.hostname);
console.log(parsed.q);
console.log(parsed.s);Expected output
example.com merhaba 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the modern way to get a URL's query parameters?
url.searchParams.get("q")- Only regex
- Only String.split("&")
- URLSearchParams veya url.searchParams Correct answer
- Only the querystring module
Explanation: URLSearchParams is the modern and recommended way.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
new URL() |
Parses address |
URLSearchParams |
Manages query |
pathname |
Path component |
querystring |
Legacy query module |
3 Complete the URL construction
const url = new ____(adres);
const url = new URL(adres);
Explanation: new URL parses the address.