Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 644
Bobos Avatar asked Oct 23 '25 14:10

Bobos


1 Answers

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.

like image 117
jAndy Avatar answered Oct 26 '25 03:10

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!