When you’re handling string data, you commonly need to format strings quickly. Node.js provides a rudimentary string formatting method in the util
module that handles many string formatting needs. The util.format()
function accepts a formatter string as the first argument and returns a formatted string. The following is the syntax for the format()
method, where format
is the formatter string and [...]
represents the arguments that follow:
util.format(format, [...])
The format
argument is a string that can contain zero or more placeholders. Each placeholder begins with a %
character and is eventually replaced with the converted string value from its corresponding argument. The first formatter placeholder represents the second argument and so on. The following placeholders are supported:
%d: Specifies a number (can be integer or float).
%j: Specifies a JSON stringifyable object.
%: If left empty, does not act as a placeholder.
Keep in mind the following when using format()
:
When there are not as many arguments as placeholders, the placeholders, such as %s
, are not replaced. For example:
util.format('%s = %s', 'Item1'), // 'Item1':%s'
When there are more arguments than placeholders, the extra arguments are converted to strings and concatenated with a space delimiter. For example
util.format('%s = %s', 'Item1', 'Item2', 'Item3'), // 'Item1 = Item2 Item3'
If the first argument is not a format string, then util.format()
converts each argument to a string, concatenates them together using a space delimiter, and then returns the concatenated string. For example:
util.format(1, 2, 3); // '1 2 3'