10

Is it possible to call a C#-like String.Format() function in JQuery?

Nam G VU
  • 30,868
  • 67
  • 216
  • 353

2 Answers2

17

Equivalent of String.format in JQuery

Here is the format function...

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;
}
Community
  • 1
  • 1
Bastardo
  • 4,106
  • 9
  • 40
  • 59
  • Had to change a couple of lines otherwise it malfunctioned when one of the arguments was null: var replacement = arguments[i + 1]; s = s.replace(reg, replacement == null ? "" : replacement); – DeclanMcD Mar 13 '17 at 17:30
12

Checkout format() that's part of the validation plugin that does C# like string formatting.

jp2code
  • 25,449
  • 37
  • 148
  • 261
Bala R
  • 104,615
  • 23
  • 192
  • 207