Query strings
The query string is the part of a URL after the question mark, holding key=value pairs.
In this page:
Syntax
const url = new URL(req.url, 'http://localhost');
url.searchParams.get('name');
Query strings
Parse it with the URL and URLSearchParams classes: new URL(req.url, base).searchParams.get("q"). The older querystring module also works. Values are always strings and repeated keys can be read with getAll.
Note:
Use URLSearchParams instead of hand-splitting strings.
Example: Query strings
const url = new URL("http://localhost/search?q=node+js&page=2&tag=a&tag=b");
console.log(url.searchParams.get("q"));
console.log(Number(url.searchParams.get("page")) + 1);
console.log(url.searchParams.getAll("tag"));
console.log(Object.fromEntries(url.searchParams));
// Output:
// node js
// 3
// [ 'a', 'b' ]
// { q: 'node js', page: '2', tag: 'b' }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Splitting on & manually
- Forgetting values are strings
- Not decoding percent-encoded characters
Chapter Summary
- Use URL and URLSearchParams
- get returns a string
- getAll handles repeats
- Decoding is automatic
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: