4

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.

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 don't know the number of placeholders too.
@Bobos Updated. Hope that helps.
Great answer! Thank's! It seems that I need to better learn javascript ;)
1

You could also use ...:

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

This also works with variables:

util.format('My name is %s %s', ...myArray);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.