new URL(input[, base])
input
<string> 要解析的絕對或相對輸入 URL。如果input
是相對的,則需要base
。如果input
是絕對的,則忽略base
。如果input
不是字符串,則首先是converted to a string。base
<string> 如果input
不是絕對的,則要解析的基本 URL。如果base
不是字符串,則首先是converted to a string。
通過解析相對於 base
的 input
創建一個新的 URL
對象。如果 base
作為字符串傳遞,它將被解析為等同於 new URL(base)
。
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo
URL 構造函數可作為全局對象的屬性進行訪問。也可以從內置的 url 模塊導入:
import { URL } from 'node:url'; console.log(URL === globalThis.URL); // Prints 'true'.
console.log(URL === require('node:url').URL); // Prints 'true'.
如果 input
或 base
不是有效的 URL,則會拋出 TypeError
。請注意,將努力將給定的值強製轉換為字符串。例如:
const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/
input
的主機名中出現的 Unicode 字符將使用 Punycode 算法自動轉換為 ASCII。
const myURL = new URL('https://測試');
// https://xn--g6w251d/
此函數僅在 node
可執行文件在啟用 ICU 的情況下編譯時可用。如果不是,則域名原封不動地通過。
如果事先不知道 input
是否是絕對 URL 並且提供了 base
,建議驗證 URL
對象的 origin
是否是預期的。
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/
相關用法
- Node.js new URLSearchParams(obj)用法及代碼示例
- Node.js new URLSearchParams(iterable)用法及代碼示例
- Node.js new URLSearchParams(string)用法及代碼示例
- Node.js new assert.AssertionError(options)用法及代碼示例
- Node.js new AsyncResource(type[, options])用法及代碼示例
- Node.js new stream.Duplex(options)用法及代碼示例
- Node.js new stream.Readable([options])用法及代碼示例
- Node.js new Console(options)用法及代碼示例
- Node.js new crypto.Certificate()用法及代碼示例
- Node.js new stream.Writable([options])用法及代碼示例
- Node.js new Agent([options])用法及代碼示例
- Node.js new vm.SourceTextModule(code[, options])用法及代碼示例
- Node.js new stream.Transform([options])用法及代碼示例
- Node.js new PerformanceObserver(callback)用法及代碼示例
- Node.js new assert.CallTracker()用法及代碼示例
- Node.js net.isIP(input)用法及代碼示例
- Node.js net.createConnection(options[, connectListener])用法及代碼示例
- Node.js net.isIPv6(input)用法及代碼示例
- Node.js net.Server.address()用法及代碼示例
- Node.js net.createServer([options][, connectionListener])用法及代碼示例
- Node.js net.Server.listen()用法及代碼示例
- Node.js net.Socket.setTimeout(timeout[, callback])用法及代碼示例
- Node.js net.BlockList.check(address[, type])用法及代碼示例
- Node.js net.isIPv4(input)用法及代碼示例
- Node.js ServerHttp2Stream http2stream.pushStream(headers[, options], callback)用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 new URL(input[, base])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。