借助url.format()方法,我们能够根据需要格式化主机名。我们有其他类型的其他参数,可用于生成主机名或根据需要更改主机名。
用法:url.format(URL[, options])
参数:
- auth是布尔值,如果为true,则必须提供用户名和密码。
 - fragment如果为true,则应包含片段,否则不包含。
 - search如果为true,则提供搜索查询,否则不提供。
 - unicode如果为true,则应直接对主机名中出现的unicode字符进行编码,否则不进行编码。
 
返回:返回一个新生成的URL或主机名
范例1:在此示例中,我们首先将url模块导入node中。然后使用以下网址生成或格式化随机网址url.format()方法。
// node program to demonstrate the   
//  url.format(URL[, options]) 
    
//importing the module 'url'  
const url = require('url'); 
    
// creating and initializing myURL  
var myURL = new URL(''https://abc:xyz@example.com#geeks');  
    
// Display href value of myURL before change  
console.log("Before Change");  
console.log(myURL.href);  
    
// using format method 
myURL = url.format(myURL, { fragment:true,  
    unicode:true, auth:false }); 
    
// Display href value of myURL after change  
console.log("After Change");  
console.log(myURL.href); 输出:
Before Change 'https://abc:xyz@example.com#geeks' After Change 'https://example.com/#geeks'
范例2:
// node program to demonstrate the   
//  url.format(URL[, options]) 
    
//importing the module 'url'  
const url = require('url'); 
    
// creating and initializing myURL  
var myURL = new URL('https://geeksforgeeks');  
    
// Display href value of myURL before change  
console.log("Before Change");  
console.log(myURL.href);  
    
// using format method 
console.log("After Change");  
console.log(url.format(myURL, { fragment:false, 
    unicode:true, auth:false }));输出:
Before Change https://geeksforgeeks After Change https://geeksforgeeks
相关用法
- Node.js URL.pathToFileURL用法及代码示例
 - Node.js URL.fileURLToPath用法及代码示例
 - Node.js URLSearchParams.has()用法及代码示例
 - Node.js URL.href用法及代码示例
 - Node.js URL.password用法及代码示例
 
注:本文由纯净天空筛选整理自Jitender_1998大神的英文原创作品 Node | URL.format API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
