Search code examples
javascriptarraysnode.js

nodeJS util.format passing an array


I am using util.format to format a string like this:

util.format('My name is %s %s', ['John', 'Smith']);

The fact that the second parameter is an array: ['John', 'Smith'], prevents my code from replacing the second %s. But i need it to be an array because I don't know the exact number of the arguments that the string might have.

Do you have any solution to my problem? Thank's in advance.

EDIT: The string that contains the placeholders is not a predefined static string. I read it from a file so the placeholders might be anywhere in the string. For the same reason I also don't know the number of placeholders.


Solution

  • You can make use of JavaScript's Function.prototype.apply to pass in arguments to a function from an Array source. This could look like

    util.format.apply(util,['My name is %s %s','John', 'Smith']);
    

    Of course you would need to .unshift() your placeholder string into that array as well beforehand.