Node.js URL.format(urlObject) API
Last Updated :
14 Jun, 2022
The URL.format(urlObject) is the inbuilt API provided by URL class, which takes an object or string and return a formatted string derived from that object or string.
Syntax:
const url.format(urlObject)
If the urlObject is not an object or string, then it will throw a TypeError.
Return value: It returns string derived from urlObject.
The urlObject can have the following fields or keys:
- protocol
- slashes
- auth
- hostname
- host
- port
- pathname
- search
- query
- hash
The formatting process is as follows:
Example 1
const url = require( 'url' );
var urlObject={
protocol: 'https' ,
hostname: 'example.com' ,
port: 1800,
pathname: 'sample/path' ,
query: {
page: 1,
format: 'json'
},
hash: 'first'
}
var sampleUrl=url.format(urlObject);
console.log(sampleUrl.toString());
|
Output: https://example.com:1800/sample/path?page=1&format=json#first
Example 2
const url = require( 'url' );
var urlObject={
protocol: 'prct' ,
slashes: false ,
host: 'example.com' ,
auth: 'abc' ,
pathname: '/sample/path' ,
search: 'something' ,
hash: 'first'
}
var sampleUrl=url.format(urlObject);
console.log(sampleUrl.toString());
|
Output: prct:abc@example.com/sample/path?something#first
NOTE: The above program will compile and run by using the node fileName.js command.
Reference:
https://nodejs.org/api/url.html#url_url_format_urlobject
Share your thoughts in the comments
Please Login to comment...