URL()
构造函数返回一个新创建的 URL
对象,表示由一组参数定义的 URL。
如果给定的基本 URL 或生成的 URL 不是有效的 URL 链接,则会抛出一个TypeError
。
Note: 此特性在 Web Worker 中可用。
语法
const url = new URL(url [, base])
参数
异常
异常 | 解释 |
---|---|
TypeError |
url 若为绝对 URL)或 base + url (若为相对 URL)是一个无效的 URL 链接。 |
示例
let m = 'https://developer.mozilla.org';
let a = new URL("/", m); // => 'https://developer.mozilla.org/'
let b = new URL(m); // => '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'
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
new URL('http://www.example.com', ); // => 'http://www.example.com/'
new URL('http://www.example.com', b); // => 'http://www.example.com/'
new URL("//foo.com", "https://example.com") // => 'https://foo.com' (see relative URLs)
规范
规范 | 状态 | 备注 |
---|---|---|
URL URL.URL() |
Living Standard | Initial definition. |
浏览器兼容性
BCD tables only load in the browser
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.
参见
- 接口:
URL