URLSearchParams
- Node.js course
- Intermediate
- Lesson 107/116
- 5 min
Learn query strings with URLSearchParams.
URLSearchParams
URLSearchParams parses and manages the query string (?key=value) of a URL. You create one with new URLSearchParams("a=1&b=2"); you get values with .get("a").
Example: const params = new URLSearchParams("q=hello&s=1"); params.get("q"); returns "hello". .has("s") checks whether a key exists. .set("a", "5") updates an existing key; .append("c", "3") adds a new key. .toString() gives back the query string. To get the query from a URL object, the url.searchParams property is handy; it is already a URLSearchParams object. The query string supports multiple values: for ?a=1&a=2 .getAll("a") gives ["1", "2"].
set, append and has
URLSearchParams does not only read; it also writes. .set(key, value) updates an existing key or creates one. .append(key, value) adds a second value to the same key. .has(key) checks presence.
Example: const p = new URLSearchParams("a=1"); p.set("a", "5"); p.append("b", "2"); console.log(p.toString()); gives a=5&b=2. .delete("b") removes a key. .sort() sorts keys alphabetically. Together these methods let you build a query string programmatically: add filters from user input, append to a URL with .toString(). The difference: set leaves one value, append allows multiple.
Practice Extract query parameters
Create a URL with const url = new URL("https://example.com/path?q=merhaba&s=1");. Get params with const params = new URLSearchParams(url.search);. Print values with console.log(params.get("q")) and console.log(params.get("s")).
Starter code
// Create a URL
// write here
// Create URLSearchParams
// write here
// Print q and s values
// write hereSample solution
const url = new URL("https://example.com/path?q=merhaba&s=1");
const params = new URLSearchParams(url.search);
console.log(params.get("q"));
console.log(params.get("s"));Expected output
merhaba 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the get call
const q = params.____("q");
const q = params.get("q");
Explanation: get retrieves a key's value.
2 Match each method to its function
| Term | Meaning |
|---|---|
get |
Gets value |
set |
Updates value |
append |
Adds new value |
has |
Checks presence |
3 What does params.get("yok") return?
new URLSearchParams("a=1").get("yok")- Throws an error
- undefined dize
- null Correct answer
- An empty string ""
Explanation: A missing key returns null.