new URL(input[, base])
input<string> 要解析的绝对或相对输入 URL。如果input是相对的,则需要base。如果input是绝对的,则忽略base。如果input不是字符串,则会先进行 转换为字符串。base<string> 如果input不是绝对路径,则用作解析的基础 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'.如果 input 或 base 不是有效的 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/ 此功能仅在 node 可执行文件在编译时启用了 重症监护室 的情况下可用。如果未启用,域名将原样传递。
🌐 This feature is only available if the node executable was compiled with
ICU enabled. If not, the domain names are passed through unchanged.
在不确定 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/