URL()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
URL()
构造函数返回一个新创建的 URL
对象,该对象表示由参数定义的 URL。
如果给定的基本 URL 或生成的 URL 不是有效的 URL,则会抛出 JavaScript TypeError
异常。
备注: 此特性在 Web Worker 中可用。
语法
js
new URL(url)
new URL(url, base)
参数
异常
异常 | 解释 |
---|---|
TypeError |
url (若为绝对 URL)或 base + url (若为相对 URL)是一个无效的 URL 链接。 |
示例
js
// 基准 URL:
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'
// 无效 URL:
new URL("/en-US/docs", "");
// 抛出 TypeError 异常:'' is not a valid URL
new URL("/en-US/docs");
// 抛出 TypeError 异常:'/en-US/docs' is not a valid URL
// 其他示例:
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 早于 79 的版本会移除查询参数)
new URL("/a", "https://example.com/?query=1");
// => 'https://example.com/a'(见相对 URL)
new URL("//foo.com", "https://example.com");
// => 'https://foo.com/'(见相对 URL)
规范
Specification |
---|
URL # dom-url-url |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
URL() constructor |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Partial support
- Partial support
- See implementation notes.
- Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.