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.

JavascriptForm Validation

Code

javascriptsnippet
24 lines
const candidates = [
  'https://api.example.com/v2/orders?limit=5',
  '//cdn.example.com/lib.js',
  'mailto:ops@example.com',
  '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

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