URL And SearchParams Safe Building
Compose URLs with the URL API and searchParams so encoding, duplicate keys, and relative bases are handled by the platform.
Code
const url = new URL('https://api.example.com/v2/search');
// searchParams 负责编码:空格、&、中文都不用手写转义
url.searchParams.set('q', 'rust & go');
url.searchParams.append('tag', 'async');
url.searchParams.append('tag', 'streams');
url.searchParams.set('limit', '20');
console.log(url.toString());
console.log('q =', url.searchParams.get('q'));
console.log('tags =', url.searchParams.getAll('tag'));
// 删除与遍历
url.searchParams.delete('limit');
for (const [key, value] of url.searchParams) {
console.log(key, '=>', value);
}
// 相对基址解析
const resolved = new URL('../orders/42', 'https://api.example.com/v2/search');
console.log('resolved:', resolved.href);Inside the snippet
Repetition is confined to for (const [key, value] of url.searchParams) — the rest of the file is straight-line. The async parts await their results, which keeps ordering predictable.
The file’s state is a handful of top-level bindings: url, resolved.
Putting it to use
The demo output is labeled (q =, tags =, resolved:), so every printed line maps back to its originating operation.
Core lines
const resolved = new URL('../orders/42', 'https://api.example.com/v2/search');
const url = new URL('https://api.example.com/v2/search');
url.searchParams.append('tag', 'streams');
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.URL Encoder & DecoderEncode and decode URLs and their components safely. Switch between encodeURIComponent and encodeURI modes to handle query parameters, paths, and special characters.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `url`, `resolved`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.