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.

有帮助吗?

解决方案

If you don't know how many variables are in that array, how do you know how many placeholders to define in your string ?

I'd suggest you only use one placeholder and just .join() the array, like

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


Update

I guess I got you wrong there, you can make usage of JavaScripts 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 aswell beforehand.

其他提示

Do a for-each loop for every string object in table and replace every time one %s. (for example ['John', 'Smith'] has 2 strings)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top