URLSearchParams Build And Mutate Query Strings
Build, read, and mutate query strings with URLSearchParams: append and getAll handle repeated keys, set keeps one, and missing keys return null.
Code
// URLSearchParams: 查询串的构建、读取与变更,无需手写拼接
const params = new URLSearchParams({ q: 'array methods', page: '2' });
params.append('tag', 'es2023');
params.append('tag', 'es2024');
console.log(params.toString());
console.log('tags:', params.getAll('tag').join('|'));
console.log('missing:', params.get('author')); // null,不会抛错
params.set('page', '3'); // 同名键只保留一个
params.delete('q');
console.log([...params.entries()].map(([key, value]) => `${key}=${value}`).join('&'));
console.log('has tag:', params.has('tag'), 'size:', params.size);
params.forEach((value, key) => console.log('pair:', key, '=', value));Output
Captured from a sandboxed run of this snippet in the build pipeline.
q=array+methods&page=2&tag=es2023&tag=es2024
tags: es2023|es2024
missing: null
page=3&tag=es2023&tag=es2024
has tag: true size: 3
pair: page = 3
pair: tag = es2023
pair: tag = es2024What the code does
Top-level bindings params hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (tags:, missing:, has tag:), so every printed line maps back to its originating operation.
Statements that matter
const params = new URLSearchParams({ q: 'array methods', page: '2' });
params.set('page', '3'); // 同名键只保留一个
params.delete('q');
params.append('tag', 'es2023');
Interactive Tools for This Topic
Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `params`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.