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.

JavascriptData Fetching

Code

snippet
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

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`.