URL: URL() constructor


目录

The URL() constructor returns a newly created URL object representing the URL defined by the parameters.

If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError exception is thrown.

Syntax

new URL(url)
new URL(url, base)

Parameters

NOTE: The url and base arguments will each be stringified from whatever value you pass, such as an HTMLAnchorElement or HTMLAreaElement element, just like with other Web APIs that accept a string. In particular, you can use an existing URL object for either argument, and it will be stringified from the object's href property.

Exceptions

Examples

Here are some examples of using the constructor.

NOTE: Resolving relative references to a URL provides additional examples demonstrating how different url and base values are resolved to a final absolute URL.

// Base URLs:
let baseUrl = "https://developer.mozilla.org";

let a = new URL("/", baseUrl);
// => 'https://developer.mozilla.org/'

let b = new URL(baseUrl);
// => 'https://developer.mozilla.org/'

new URL("en-US/docs", b);
// => 'https://developer.mozilla.org/en-US/docs'

let d = new URL("/en-US/docs", b);
// => 'https://developer.mozilla.org/en-US/docs'

new URL("/en-US/docs", d);
// => 'https://developer.mozilla.org/en-US/docs'

new URL("/en-US/docs", a);
// => 'https://developer.mozilla.org/en-US/docs'

new URL("/en-US/docs", "https://developer.mozilla.org/fr-FR/toto");
// => 'https://developer.mozilla.org/en-US/docs'

Here are some examples of invalid URLs:

new URL("/en-US/docs", "");
// Raises a TypeError exception as '' is not a valid URL

new URL("/en-US/docs");
// Raises a TypeError exception as '/en-US/docs' is not a valid URL

// Other cases:

new URL("http://www.example.com");
// => 'http://www.example.com/'

new URL("http://www.example.com", B);
// => 'http://www.example.com/'

new URL("", "https://example.com/?query=1");
// => 'https://example.com/?query=1' (Edge before 79 removes query arguments)

new URL("/a", "https://example.com/?query=1");
// => 'https://example.com/a' (see relative URLs)

new URL("//foo.example", "https://example.com");
// => 'https://foo.example/' (see relative URLs)

Specifications

Browser compatibility

See also


版本号 #3
由 壳壳虫 创建于 2026-10-31 03:27:53 UTC
由 cocobook-sync 更新于 2026-11-04 17:35:02 UTC