Introduction
URLSearchParams helps you easily read and change the parts of a web address that come after the question mark, called query strings.
Jump into concepts and practice - no test required
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();
const params = new URLSearchParams('name=Alice&age=25'); console.log(params.get('name'));
const params = new URLSearchParams(); params.append('color', 'blue'); params.append('size', 'medium'); console.log(params.toString());
const params = new URLSearchParams('page=1&sort=asc'); params.set('page', '2'); console.log(params.toString());
const params = new URLSearchParams('q=search&lang=en'); params.delete('lang'); console.log(params.toString());
import { URLSearchParams } from 'url'; const queryString = 'product=book&price=20¤cy=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());
URLSearchParams class in Node.js primarily help you do?URLSearchParams object from a query string in Node.js?new keyword and accepts a query string like '?name=John&age=30'.new or passing an object directly without conversion are invalid.new with query string [OK]const params = new URLSearchParams('color=blue&size=medium');
params.set('size', 'large');
console.log(params.toString());set method updates the value of the 'size' parameter from 'medium' to 'large'.toString() method returns the query string with updated parameters in the order they were added.const params = new URLSearchParams('page=1&limit=10');
params.append('page', 2);
console.log(params.get('page'));{ search: 'books', page: 2, filter: '' } but want to exclude empty values. Which code correctly creates the query string using URLSearchParams?