Open In App

Node.js URL.format(urlObject) API

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:

    1. Initially, an empty string (‘’ say result) is created and then following parameters are looked for in order.

    2. urlObject.protocol: string

    3. urlObject.slashes: boolean
    4. urlObject.auth: string
    5. urlObject.host: string
    6. urlObject.hostname: string
    7. urlObject.port: (number | string)
    8. urlObject.pathname: string
    9. urlObject.search: string
    10. urlObject.query: Object
    11. urlObject.hash: string
    12. Finally, the result is returned.

Example 1




/*
  node program to demonstrate the URL.format API.
*/  
    
//importing the module 'url'
const url = require('url');
  
//creating and initializing urlObject
var urlObject={
        protocol: 'https',
        hostname: 'example.com',
        port: 1800,
        pathname: 'sample/path',
        query: {
                page: 1,
                format: 'json'
        },
        hash: 'first'
    }
  
//getting the derived URL from urlObject using the url.format function
var sampleUrl=url.format(urlObject);
  
//Display the returned value
console.log(sampleUrl.toString());
   

Output: https://example.com:1800/sample/path?page=1&format=json#first

Example 2




/*
  node program to demonstrate the URL.format API.
*/  
    
//importing the module 'url'
const url = require('url');
  
//creating and initializing urlObject
var urlObject={
        protocol: 'prct',
        slashes: false,
        host: 'example.com',
        auth: 'abc',
        pathname: '/sample/path',
        search: 'something',
        hash: 'first'
    }
  
//getting the derived URL from urlObject using the url.format function
var sampleUrl=url.format(urlObject);
  
//Display the returned value
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


Article Tags :