url.format(URL[, options])
返回 WHATWG 网址对象的网址 String
表示的可自定义的序列化。
网址对象具有 toString()
方法和 href
属性,用于返回网址的字符串序列化。
但是,这些都不能以任何方式自定义。
url.format(URL[, options])
方法允许对输出进行基本的自定义。
import url from 'url';
const myURL = new URL('https://a:b@測試?abc#foo');
console.log(myURL.href);
// 打印 https://a:b@xn--g6w251d/?abc#foo
console.log(myURL.toString());
// 打印 https://a:b@xn--g6w251d/?abc#foo
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// 打印 'https://測試/?abc'
const url = require('url');
const myURL = new URL('https://a:b@測試?abc#foo');
console.log(myURL.href);
// 打印 https://a:b@xn--g6w251d/?abc#foo
console.log(myURL.toString());
// 打印 https://a:b@xn--g6w251d/?abc#foo
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// 打印 'https://測試/?abc'
URL
<URL> A WHATWG URL objectoptions
<Object>auth
<boolean>true
if the serialized URL string should include the username and password,false
otherwise. Default:true
.fragment
<boolean>true
if the serialized URL string should include the fragment,false
otherwise. Default:true
.search
<boolean>true
if the serialized URL string should include the search query,false
otherwise. Default:true
.unicode
<boolean>true
if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded. Default:false
.
- Returns: <string>
Returns a customizable serialization of a URL String
representation of a
WHATWG URL object.
The URL object has both a toString()
method and href
property that return
string serializations of the URL. These are not, however, customizable in
any way. The url.format(URL[, options])
method allows for basic customization
of the output.
import url from 'url';
const myURL = new URL('https://a:b@測試?abc#foo');
console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo
console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'
const url = require('url');
const myURL = new URL('https://a:b@測試?abc#foo');
console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo
console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'