6

Possible Duplicate:
JavaScript equivalent to printf/string.format

I'm not sure the exact term (string substitution?) but many languages (C, VB, C#, etc.) offer similar mechanisms for constructing string dynamically. The following is an example in C#:

string firstName = "John";
string lastName = "Doe";
string sFinal = string.Format(" Hello {0} {1} !", firstName, lastName);

I'd would like to accomplish the same thing in JavaScript. Can anyone shed some light?

Thanks,

Community
  • 1
  • 1
archenil
  • 133
  • 2
  • 8

1 Answers1

4

JavaScript does not yet have this functionality natively. You'll have to use concatenation:

var firstName = "John";
var lastName = "Doe";
var sFinal = " Hello " + firstName + " " + lastName + " !";

That sucks? True. But this is the world we live in.


As pointed out by @PeterSzymkowski, you can use this JavaScript implementation of the C/PHP sprintf function.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • [World we live in is not that bad](http://www.diveintojavascript.com/projects/javascript-sprintf) – Peter Jan 28 '13 at 02:57
  • @PeterSzymkowski - True, which is why I said that JavaScript does not support this *natively*. I'll add that link to my answer. – Joseph Silber Jan 28 '13 at 02:58