URL.canParse Guards Invalid Input
Validate URLs before constructing: canParse rejects bare protocol-relative strings, accepts opaque mailto schemes, and takes a base for relatives.
Code
const candidates = [
'https://api.example.com/v2/orders?limit=5',
'//cdn.example.com/lib.js',
'mailto:[email protected]',
'not a url at all',
];
for (const candidate of candidates) {
// canParse 先验证:无效输入不会让 new URL 抛出异常
if (URL.canParse(candidate)) {
const url = new URL(candidate);
console.log('ok :', url.protocol, url.host || '(opaque)');
} else {
console.log('bad :', JSON.stringify(candidate));
}
}
// 相对地址需要 base:canParse 接受第二个参数
const base = 'https://docs.example.com/guide/';
const relative = './auth.html#tokens';
console.log('with base:', URL.canParse(relative, base));
const resolved = new URL(relative, base);
console.log('resolved :', resolved.href);
console.log('hash :', resolved.hash);How it works
for (const candidate of candidates) is the loop that carries the per-item work.
Module-level bindings hold the data — candidates, base, relative, resolved — with no function scope in between.
Using it
Running the file prints labeled results such as ok :, bad :, with base: — each operation’s effect is visible in the output.
Key statements
const base = 'https://docs.example.com/guide/';
const resolved = new URL(relative, base);
const relative = './auth.html#tokens';
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `candidates`, `base`, `relative`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.