10

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

3
  • Are you use the ASP.NET MVC or Web Forms? Commented May 10, 2011 at 20:58
  • look at this question Equivalent of String.format in JQuery Commented May 10, 2011 at 21:00
  • @Serghei I'd like to apply the best of each technology around my works. Thanks Commented May 20, 2011 at 14:28

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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);
12

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

2 Comments

The link was broken, so I fixed it.
+1 because although it's not purely javascript, it's a better option than a custom script if one is already using jquery.validate

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.