Is it possible to call a C#-like String.Format() function in JQuery?
Asked
Active
Viewed 3.2k times
10
-
Are you use the ASP.NET MVC or Web Forms? – Sergey K May 10 '11 at 20:58
-
@Serghei I'd like to apply the best of each technology around my works. Thanks – Nam G VU May 20 '11 at 14:28
-
look at this question [Equivalent of String.format in JQuery](http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery) – Sergey K May 10 '11 at 21:00
2 Answers
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; }
-
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
-
-
+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