new URL(input[, base])


  • input <string> 要解析的输入URL
  • base <string> | <URL> 如果“input”是相对URL,则为要解析的基本URL。

通过将input解析到base上创建一个新的URL对象。如果base是一个字符串,则解析方法与new URL(base)相同。

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

如果inputbase是无效URLs,将会抛出TypeError。请注意给定值将被强制转换为字符串。例如:

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

存在于input主机名中的Unicode字符将被使用Punycode算法自动转换为ASCII。

const { URL } = require('url');
const myURL = new URL('https://你好你好');
  // https://xn--6qqa088eba/

Note: This feature is only available if the node executable was compiled with ICU enabled. If not, the domain names are passed through unchanged.

  • input <string> The absolute or relative input URL to parse. If input is relative, then base is required. If input is absolute, the base is ignored.
  • base <string> | <URL> The base URL to resolve against if the input is not absolute.

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

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/

Unicode characters appearing within the hostname of input will be automatically converted to ASCII using the Punycode algorithm.

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

This feature is only available if the node executable was compiled with ICU enabled. If not, the domain names are passed through unchanged.

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/