2 min read
•Question 18 of 62easyHow to work with query strings in Node.js?
Parsing and formatting URL query strings.
What You'll Learn
- Parsing query strings
- Stringifying objects
- URLSearchParams alternative
Querystring Module
code.jsJavaScript
const querystring = require('querystring');
// Parse query string to object
const parsed = querystring.parse('name=John&age=30&city=NYC');
console.log(parsed);
// { name: 'John', age: '30', city: 'NYC' }
// Stringify object to query string
const str = querystring.stringify({ name: 'John', age: 30 });
console.log(str);
// 'name=John&age=30'
// With custom separator and equals
const custom = querystring.stringify(
{ a: 1, b: 2 },
';', // separator
':' // equals
);
console.log(custom); // 'a:1;b:2'
// Escape special characters
const escaped = querystring.escape('hello world');
// 'hello%20world'
// Unescape
const unescaped = querystring.unescape('hello%20world');
// 'hello world'URLSearchParams (Modern Alternative)
code.jsJavaScript
const params = new URLSearchParams('name=John&age=30');
console.log(params.get('name')); // 'John'
params.set('city', 'NYC');
console.log(params.toString()); // 'name=John&age=30&city=NYC'