Node.js
URLSearchParams
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.
Exercise 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")).
Show example 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"));
Test yourself
-
Complete the get call
const q = params.____("q");
Show answer
const q = params.get("q");
-
Match each method to its function
- get
- Gets value
- set
- Updates value
- append
- Adds new value
- has
- Checks presence
-
What does params.get("yok") return?
new URLSearchParams("a=1").get("yok")
- Throws an error
- undefined dize
- null
- An empty string ""
Show answer
null — A missing key returns null.
Next lesson: URL properties