← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 4 of 7

Query strings

The query string is the part of a URL after the question mark, holding key=value pairs.

In this page:

  1. Query strings
Syntax
javascript
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

javascript
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
  1. Splitting on & manually
  2. Forgetting values are strings
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.