How to parse and build a query string
Short answer
URLSearchParams reads parameters from a query string:
const params = new URLSearchParams('?q=coffee&page=2&sort=price');
console.log(params.get('q'), params.get('page'));
console.log(params.get('missing'));Output:
coffee 2
nullBuilding a query
Pass an object, and toString() returns a ready string with special characters encoded:
const params = new URLSearchParams({ q: 'tea & cake', page: 1 });
console.log(params.toString());Output:
q=tea+%26+cake&page=1Several values for one key
append() adds another value, and getAll() returns all of them:
const params = new URLSearchParams();
params.append('tag', 'js');
params.append('tag', 'css');
console.log(params.toString());
console.log(params.getAll('tag').join(', '));Output:
tag=js&tag=css
js, cssInto an object
Object.fromEntries() turns parameters into an ordinary object:
const params = new URLSearchParams('color=red&size=M');
console.log(JSON.stringify(Object.fromEntries(params)));Output:
{"color":"red","size":"M"}Common mistake
All values are strings. Convert numbers explicitly, otherwise + glues strings together:
const params = new URLSearchParams('page=2');
console.log(params.get('page') + 1);
console.log(Number(params.get('page')) + 1);Output:
21
3Functions used in this recipe
- URLSearchParams — Reads and builds URL query parameters (the part after ?).
- URL — Parses an address into parts and builds it back.