new URL(input[, base])
-
input
<string> 要解析的绝对或相对的输入网址。如果input
是相对的,则需要base
。如果input
是绝对的,则忽略base
。如果input
不是字符串,则首先是 转换为字符串。¥
input
<string> The absolute or relative input URL to parse. Ifinput
is relative, thenbase
is required. Ifinput
is absolute, thebase
is ignored. Ifinput
is not a string, it is converted to a string first. -
base
<string> 如果input
不是绝对的,则为要解析的基本网址。如果base
不是字符串,则首先是 转换为字符串。¥
base
<string> The base URL to resolve against if theinput
is not absolute. Ifbase
is not a string, it is converted to a string first.
通过相对于 base
解析 input
来创建新的 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 模块中导入:
¥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
不是有效的网址,则将抛出 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
是否是绝对的网址并且提供了 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/