The Wayback Machine - https://web.archive.org/web/20240808142207/https://www.geeksforgeeks.org/node-js-util-format-method/
Open In App

Node.js util.format() Method

Last Updated : 05 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The util.format() (Added in v0.5.3) method is an inbuilt application programming interface of the util module which is like printf format string and returns a formatted string using the first argument. The formatted string contains zero or more format specifiers in which the corresponding argument value is converted and replaced. It is used as a debugging tool in a synchronous method hence, it can have a significant performance overhead that could block the event loop. It is recommended not to use this function in a hot code path.

Syntax: 

util.format(format[, ...args])

Parameters: This method accepts two parameters as mentioned above and described below:

  • format: It consists of specifiers of <string> type, which is like printf format string.
  • args: It is the <string> type list of arguments.

Supported specifiers are:

  • %%: It replaces the specifier with a single percent sign (‘%%’/‘%’) and doesn’t consume any argument even if it is provided.
  • %s (String): It converts all values according to the given format except Object, BigInt, and -0. Objects that have no user-defined toString function are inspected using util.inspect() and BigInt values are represented with n.
  • %c(CSS): If any CSS is passed, it will be skipped. Usually, this specifier is ignored.
  • %d (Number): It converts all values according to the given format except Symbol and BigInt.
  • %i (parseInt()): It parses a <string> and returns an integer, it is used for all values except BigInt and Symbol.
  • %f (parseFloat()): It parses a string and returns a floating-point number, it is used for all values except Symbols.
  • %j (JSON): No complicated parsing or translations, if there are circular references in the argument then it is replaced with the string ‘[Circular]’.
  • %o(Object): It is a string representation of an object with generic JavaScript object formatting. Similar to util.inspect(). It shows the full object along with non-enumerable properties and proxies.
  • %O(Object): It is similar to ‘%o’ but without options, it does not include non-enumerable properties and proxies.

Return Value: It returns the formatted string of <string> type.

Example 1: In this example, we will see the use of the util.format().

index.js 

javascript




// Node.js to demonstrate the
// util.format() method
 
// Import the util module
const util = require('util');
 
function fun1() {
    let val1 = util.format('%s:%s:%s', 'abc');
    // Returns: 'foo:%s'
 
    let val2 = util.format('%s:%s',
        'abc', 'def', 'ghi', 'jkl');
    // Returns: 'foo:bar baz'
 
    let val3 = util.format(10, 20, 30);
    // Returns: '1 2 3'
 
    let val4 = util.format('%% : %s : %d');
    // Returns: '%% %s'
 
    let val5 = util.format('%% : %s', 567);
    // Returns: '% : 567'
 
    console.log(val1, '\n', val2, '\n',
        val3, '\n', val4, '\n', val5);
}
 
// Function call
fun1();


Run the index.js file using the following command: 

node index.js

Output:

abc:
:abc:def ghi jkl
10 20 30
%% : %s : %d
% : 567

Example 2: In this example, we will see the use of the util.format().

index.js 

javascript




// Node.js program to demonstrate
// the util.format() method
 
// Import the util module
const util = require('util');
 
// Passing multiple values and
// -0 on string specifier
console.log("1.>", util.format(
    '%%: %s', 'abc', 'def', -0));
 
// Passing multiple values
console.log("2.>", util.format(
    '%%', 'abc', 'def', 'ghi'));
 
// Passing bigInt to string specifier
console.log("3.>", util.format('%s',
    'abc', 94321321321223372036854775807));
 
// Creating and passing Object along
// with null prototype and a variable
console.log("4.>", util.format('%s',
    'abc', Object.create(null,
        {
            [Symbol.toStringTag]:
            { value: 'def' }
        })));
 
// Passing string to Number specifier
console.log("5.>", util.format('%d',
    'abc', 94303685));
 
// Passing Symbol and Number to
// parseInt specifier
console.log("6.>", util.format(
    '%i', '2020 year 2021, ', 'He was 40,'
    , '10.33, ', '10, ', 10));
 
// Passing string and Numbers
// to parseFloat specifier
console.log("7.>", util.format('%f',
    '94321321321.564000 year 6546',
    'abc', 943036854775807));
 
// Passing JSON string and Number
// to JSON specifier
console.log("8.>", util.format('%j',
    '{ "name":"John", "age":31, "city":"New York" }',
    'abc', 943036854775807));
 
// Passing class, string, and Number
// to object specifier
console.log("9.>", util.format('%o',
    class Bar { }, 'abc', 943036854775807));
 
// Passing class, string, and Number
// to Object specifier
console.log("10.>", util.format('%o:%d',
    class Foo {
        get [Symbol.toStringTag]() { return 'abc'; }
    },
    'abc',
    943036854775807
));
 
// Random class
class randomClass { }
 
// Inspecting random class
console.log("11.>",
    util.inspect(new randomClass()));


Run the index.js file using the following command: 

node index.js

Output:

1.> %: abc def -0
2.> % abc def ghi
3.> abc 9.432132132122338e+28
4.> abc [Object: null prototype] [def] {}
5.> NaN 94303685
6.> 2020 He was 40, 10.33, 10, 10
7.> 94321321321.564 abc 943036854775807
8.> "{ \"name\":\"John\", \"age\":31, 
    \"city\":\"New York\" }" abc 943036854775807
9.> <ref *1> [Function: Bar] {
    [length]: 0,
    [prototype]: Bar { [constructor]: [Circular *1] },
    [name]: 'Bar'
   } abc 943036854775807
10.> <ref *1> [Function: Foo] {
    [length]: 0,
    [prototype]: Foo {
    [constructor]: [Circular *1],
    [Symbol(Symbol.toStringTag)]: [Getter]
    },
    [name]: 'Foo'
   }:NaN 943036854775807
11.> randomClass {}

Conditions:

  • If no corresponding argument is passed to the specifier then it is not replaced.
  • If multiple arguments are passed than the number of specifiers, then extra arguments will be concatenated to the returned string.
  • If ‘values’ do not belong to format string and their type is not a string then they are formatted using util.inspect() method.
  • If the first argument doesn’t have a valid format specifier, then util.format() returns concatenated arguments.

Reference: https://nodejs.org/api/util.html#util_util_format_format_args



Previous Article
Next Article

Similar Reads

How to format the current date in MM/DD/YYYY HH:MM:SS format using Node?
The current date can be formatted by using Nodejs modules like Date Object or libraries like moment.js. Table of Content Using Node.js Date ObjectUsing Moment.js LibraryMethod 1: Using Node.js Date Object:The JavaScript Date Object can be used in the program by using the following command. const date = new Date();Now on this variable date, we can a
3 min read
Node.js util.debuglog() Method
The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘). The util.debuglog() (Added in v0.11.3) method is an inbuilt application programming interface of the util module which is used to create a function that is based on the NODE_DEBUG environmen
3 min read
Node.js util.types.isMap() Method
The util.types.isMap() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isMap() method is used to determine whether the value is a built-in Map instance or not. Syntax: util.types.isMap( value ) Parameters: This method accepts a single
2 min read
Node.js util.types.isMapIterator() Method
The util.types.isMapIterator() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js internal APIs. The util.types.isMapIterator() method is used to determine whether the value is an iterator returned for a built-in Map instance or not. Syntax: util.types.isMapIterator( val
2 min read
Node.js util.types.isSetIterator() Method
The util.types.isSetIterator() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isSetIterator() method is used to determine whether the value is an iterator returned for a built-in set instance. Syntax: util.types.isSetIterator( value
2 min read
Node.js util.types.isWeakMap() Method
The util.types.isWeakMap() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isWeakMap() method is used to determine whether the value is a built-in WeakMap instance or not. Syntax: util.types.isWeakMap( value ) Parameters: This method
2 min read
Node.js util.types.isWeakSet() Method
The util.types.isWeakSet() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isWeakSet() method is used to determine whether the value is a built-in WeakSet instance or not. Syntax: util.types.isWeakSet( value ) Parameters: This method
2 min read
Node.js util.types.isBooleanObject() Method
The util.types.isBooleanObject() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isBooleanObject() method is used to determine whether the value is a Boolean object or not. Syntax: util.types.isBooleanObject( value ) Parameters: This
2 min read
Node.js util.types.isPromise() Method
The util.types.isPromise() method is an inbuilt application programming interface of the util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isPromise() method is used to determine whether the value is a built-in Promise. Syntax: util.types.isPromise( value ) Parameter: This method accepts a sin
2 min read
Node.js util.types.isTypedArray() Method
The util.types.isTypedArray() method is an inbuilt application programming interface of util module which is primarily designed to support the needs of Node.js own internal APIs. The util.types.isTypedArray() method is used to determine whether the value is a built-in TypedArray instance. Syntax: util.types.isTypedArray( value ) Parameter: This met
1 min read
three90RightbarBannerImg