new URL(input[, base])


  • input <string> 要解析的绝对或相对输入 URL。如果 input 是相对的,则必须提供 base。如果 input 是绝对的,则忽略 base。如果 input 不是字符串,则首先将其 转换为字符串
  • base <string> 如果 input 不是绝对 URL,则用作解析的基础 URL。如果 base 不是字符串,则首先将其 转换为字符串

通过将 input 相对于 base 进行解析来创建一个新的 URL 对象。如果 base 以字符串形式传入,它将被解析为等同于 new URL(base)

【Creates a new URL object by parsing the input relative to the base. If base is passed as a string, it will be parsed equivalent to new URL(base).】

const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo 

URL 构造函数可以作为全局对象上的一个属性访问。它也可以从内置的 url 模块中导入:

【The URL constructor is accessible as a property on the global object. It can also be imported from the built-in url module:】

import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').URL); // Prints 'true'.

如果 inputbase 不是有效的 URL,将会抛出 TypeError。请注意,将尝试将给定的值强制转换为字符串。例如:

【A TypeError will be thrown if the input or base are not valid URLs. Note that an effort will be made to coerce the given values into strings. For instance:】

const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/ 

input 的主机名中出现的 Unicode 字符将自动使用 Punycode 算法转换为 ASCII。

【Unicode characters appearing within the host name of input will be automatically converted to ASCII using the Punycode algorithm.】

const myURL = new URL('https://測試');
// https://xn--g6w251d/ 

在不确定 input 是否为绝对 URL 且提供了 base 的情况下,建议验证 URL 对象的 origin 是否符合预期。

【In cases where it is not known in advance if input is an absolute URL and a base is provided, it is advised to validate that the origin of the URL object is what is expected.】

let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/

myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/

myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/

myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/