10

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

Nam G VU
  • 33,193
  • 69
  • 233
  • 372

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,144
  • 9
  • 41
  • 60
  • 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.

Bala R
  • 107,317
  • 23
  • 199
  • 210
  • The link was broken, so I fixed it. –  Jan 17 '14 at 14:42
  • +1 because although it's not purely javascript, it's a better option than a custom script if one is already using jquery.validate – Farinha Feb 26 '14 at 16:33