0
0
Node.jsframework~5 mins

URLSearchParams for query strings in Node.js

Choose your learning style9 modes available
Introduction
URLSearchParams helps you easily read and change the parts of a web address that come after the question mark, called query strings.
When you want to get values from a URL's query string, like ?name=John.
When you need to add or update query parameters before sending a web request.
When you want to remove or list all query parameters from a URL.
When building web servers or clients that handle URLs dynamically.
When parsing user input from URLs in a clean and safe way.
Syntax
Node.js
const params = new URLSearchParams(queryString);

// To get a value
params.get('key');

// To set or update a value
params.set('key', 'value');

// To add a new value
params.append('key', 'value');

// To delete a key
params.delete('key');

// To convert back to string
params.toString();
The queryString is the part after '?' in a URL, like 'name=John&age=30'.
URLSearchParams automatically handles encoding special characters.
Examples
Gets the value of 'name' which is 'Alice'.
Node.js
const params = new URLSearchParams('name=Alice&age=25');
console.log(params.get('name'));
Creates query string 'color=blue&size=medium' from added parameters.
Node.js
const params = new URLSearchParams();
params.append('color', 'blue');
params.append('size', 'medium');
console.log(params.toString());
Updates 'page' from '1' to '2' in the query string.
Node.js
const params = new URLSearchParams('page=1&sort=asc');
params.set('page', '2');
console.log(params.toString());
Removes 'lang' parameter, leaving 'q=search'.
Node.js
const params = new URLSearchParams('q=search&lang=en');
params.delete('lang');
console.log(params.toString());
Sample Program
This code reads the product name, updates the price, adds a discount, removes the currency, and prints the results.
Node.js
import { URLSearchParams } from 'url';

const queryString = 'product=book&price=20&currency=USD';
const params = new URLSearchParams(queryString);

// Read a value
const product = params.get('product');

// Update price
params.set('price', '25');

// Add a new parameter
params.append('discount', '5');

// Remove currency
params.delete('currency');

// Show final query string
console.log('Product:', product);
console.log('Final query string:', params.toString());
OutputSuccess
Important Notes
URLSearchParams works well with Node.js version 10 and above.
It automatically encodes special characters like spaces or symbols when converting to string.
Use .toString() to get the full query string to use in URLs or requests.
Summary
URLSearchParams makes handling URL query strings simple and safe.
You can get, set, add, or delete query parameters easily.
It helps keep your URL building and parsing clean and readable.