Introduction
Parsing query strings helps you get the information sent in a URL after the question mark. This lets your program understand what the user wants.
Jump into concepts and practice - no test required
Parsing query strings helps you get the information sent in a URL after the question mark. This lets your program understand what the user wants.
import { parse } from 'node:querystring'; const query = 'name=alice&age=25'; const parsed = parse(query); console.log(parsed);
The parse function turns a query string into an object.
Each key-value pair in the string becomes a property in the object.
import { parse } from 'node:querystring'; const query = 'color=blue&size=medium'; const result = parse(query); console.log(result);
import { parse } from 'node:querystring'; const query = 'flag&count=10'; const result = parse(query); console.log(result);
import { parse } from 'node:querystring'; const query = 'name=John%20Doe&city=New%20York'; const result = parse(query); console.log(result);
This program takes a query string with product details and turns it into an object you can use in your code.
import { parse } from 'node:querystring'; // Example query string from a URL const urlQuery = 'product=book&price=15&available=true'; // Parse the query string into an object const parsedQuery = parse(urlQuery); // Show the parsed object console.log(parsedQuery);
Query string values are always strings after parsing.
Use URLSearchParams for more modern and flexible parsing in Node.js.
Parsing query strings converts URL parameters into easy-to-use objects.
Node.js provides a simple parse function in the querystring module.
This helps your app understand user requests from URLs.
require() to import modules in CommonJS style.const querystring = require('querystring'); correctly imports the module.const querystring = require('querystring');
const url = 'name=John&age=30';
const parsed = querystring.parse(url);
console.log(parsed);parse function converts the query string into an object with keys and values.const querystring = require('querystring');
const url = 'name=Alice&city=Wonderland';
const parsed = querystring.parse(url);
console.log(parsed.name, parsed.city);id=1&id=2&id=3. Using querystring.parse, what will the parsed object look like?id=1&id=2&id=3, the last value '3' is kept.