📜  Node.js URL.format API

📅  最后修改于: 2022-05-13 01:56:53.189000             🧑  作者: Mango

Node.js URL.format API

借助url.format()方法,我们可以根据需要格式化主机名。我们有不同类型的其他参数,可用于生成主机名或根据需要更改主机名。

示例 1:在此示例中,我们首先在 node.js 中导入url模块。然后我们使用url.format()方法生成或格式化随机 url。

// 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