0

Possible Duplicate:
JavaScript equivalent to printf/string.format

Is there a more C like way to print complex strings in javascript, preferably one which doesn't require large numbers of the + symbol and accompanying ""?

I want this:

console.log ( "Name: %s Age: %s Sex %s Wieght %s Height %s", name, age, sex, weight, height );

Instead of this:

console.log ( "Name: " + name + " Age: " + age + " Sex: " + sex + " Weight: " + weight " Height: " + height );
Community
  • 1
  • 1
puk
  • 16,318
  • 29
  • 119
  • 199
  • http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – Lance Jul 18 '12 at 21:15
  • @Lance my bad. I searched for everything except "javascript ... printf". I'll vote to close – puk Jul 18 '12 at 21:17

3 Answers3

2

This library seems to do what you want if you don't mind going third-party.

JavaScript sprintf

From article

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
wanovak
  • 6,117
  • 25
  • 32
1

Are you talking about standard window.console? It has exactly the same functionality (tested on Firefox):

console.log( "Name: %s Age: %s Sex %s Wieght %s Height %s", name, age, sex, weight, height);

Alternatively:

console.log( "Name: ", name, " Age: ", sex, " Sex ", sex, " Wieght ", weight", " Height ", height);
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

using console.log you can always do this instead of concatenation:

console.log ( "Name: ", name, " Age: ", age, " Sex: ", sex, " Weight: ", weight, " Height: " , height );
Grzegorz Kaczan
  • 21,186
  • 3
  • 19
  • 17