← 中文资源

简体中文版本

URL.parse 对非法 URL 返回 null

用 URL.parse 校验绝对与相对 URL,遇到非法输入返回 null 而不抛异常,并读取主机、端口与查询值。

阅读英文原文

实现说明

文件的主干是一个循环——for (const raw of candidates)。 candidates、page 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 host:、page:、port:——输出的每一行都能指回产生它的那次调用。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件的状态由几个模块级绑定持有:candidates、page。

核心语句

const page = URL.parse('https://example.com/docs?page=2&sort=asc');
const parsed = URL.parse(raw, 'https://example.com');

代码示例

const candidates = [
  'https://example.com/docs?page=2',
  '/relative/path',
  'mailto:dev@example.com',
  'http://',
];

for (const raw of candidates) {
  const parsed = URL.parse(raw, 'https://example.com');
  console.log(raw, '->', parsed ? parsed.href : 'null');
}

const page = URL.parse('https://example.com/docs?page=2&sort=asc');
console.log('host:', page.hostname);
console.log('page:', page.searchParams.get('page'));
console.log('port:', URL.parse('https://example.com:8443/').port || '(default)');