Node | URL.format API
With the help of url.format()method, we are able to format the hostname according to our need. We have different types of other parameters which we can use to generate the hostname or to change the hostname as required.
Syntax :
url.format(URL[, options])
Parameter :
- auth is a boolean value if true then username and password have to be provided.
- fragment if true then fragment should be included otherwise not.
- search if true then provide the search query otherwise not.
- unicode if true then unicode character appearing in the hostname should be encoded directly otherwise not.
Return : return a newly generate URL or hostname
Example 1 : In this example we first import the url module in node. Then to generate or format the random url we use the url.format() method.
// 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); |
Output :
Before Change 'https://abc:xyz@example.com#geeks' After Change 'https://example.com/#geeks'
Example 2:
// node program to demonstrate the // url.format(URL[, options]) //importing the module 'url' const url = require('url'); // creating and initializing myURL // 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 })); |
Output :
Before Change https://geeksforgeeks After Change https://geeksforgeeks
Recommended Posts:
- Node js | OS
- Why Node.js ?
- Node | URL.hash API
- Node | URL.domainToUnicode
- Node.js | pop() function
- Node | URL.protocol API
- Node | URL.pathToFileURL API
- Promises in Node.js
- Routing in Node.js
- Node | URL.host API
- Node | URLSearchParams.has()
- Node | URLSearchParams.get()
- Node | URL.domainToASCII
- Node | URL.resolve(from,to) API
- Node | URLSearchParams.set()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

