0

Possible Duplicate:
JavaScript equivalent to printf/string.format

Do we have something like C# String.Format(...) in JavaScript?

I like to be able to say String.Format('text text {0}, text text {1}', value1, value2);

and ideally as an extension method:

'text text {0}, text text {1}'.format(value1, value2);

Thanks,

Community
  • 1
  • 1
The Light
  • 26,341
  • 62
  • 176
  • 258

1 Answers1

4

here is your solution:

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

more informations here => Equivalent of String.format in jQuery

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • How is it possible to have the format method as an extension method of the string instance? e.g. accessing it with "text {0} text {1}".format(value1, value2); the benefit is having less code. – The Light Jul 21 '11 at 08:52
  • @William: https://gist.github.com/1096824 – pimvdb Jul 21 '11 at 09:07
  • How to use the above code in the same way as I use extension methods in C#? – Marek Bar Aug 28 '14 at 07:23