The util.format
function in Node.js is used to format a string by adding other data elements. In addition to character strings and numeric integers, it can also combine a string with data stored in JSON format.
The util.format
function is part of the util
module of Node.js. The syntax for it is as follows:
util.format(format_string, [...])
The util.format
function takes in two parameters:
format_string
: a string that contains the original message alongside format specifiers such as %d and %s.[...]
: a list of values, all of which are to be added to the format_string.Format specifiers are dependent on the type of data-elements that are to be added to the string. The most commonly used format specifiers supported by the util.format
function are:
Format Specifier | Usage |
---|---|
%s | Converts all values except for BigInt , -0 and Object to a string. |
%f | Used to convert a value to type Float . It does not support conversion of values of type Symbol . |
%d | Used to convert any value to Number of any type other than BigInt and Symbol . |
%j | Used to add JSON data. If a circular reference is present, the string ‘[Circular]’ is added instead. |
%% | Used to add the % sign. |
%o | Adds the string representation of an object. Note that it does not contain non-enumerable characteristics of the object. |
%O | Adds the string representation of an object. Note that it will contain all characteristics of the object, including non-enumerable ones. |
A circular reference exists if an object attempts to reference itself.
The util.format
function returns the formatted string upon successful execution.
If an incorrect format specifier is added, it is treated as a character and remains un-replaced.
The following snippet of code demonstrates how to use the util.format
function to combine JSON data, numeric values, and character strings.
Note that format specifiers are strictly dependent on the data-type of the data being added to the format string.
This program formats three character strings by adding another character string or a numerical value or some data stored in JSON format. The formatted strings are displayed using the console.log
function.
var util = require('util');company="Educative"year=2015courses= { "Area#1": 'Web-Security', "Area#2": 'Blockchain', "Area#1": 'Networking'};var formatted_one = util.format('Welcome to %s!',company);var formatted_two = util.format('We started operations in the year %d.,',year);var formatted_three = util.format('Some areas which we offer courses in are %j!', courses);console.log(formatted_one);console.log(formatted_two);console.log(formatted_three);
Free Resources