Background:
The String class has a format() method in C# which is very handy to build dynamic messages from a template.
For example,
Console.WriteLine(String.Format("Current Page Index: {0}, Total Pages: {1}", 10, 150));
The above code would generate the following outputs:
Current Page Index: 10, Total Pages: 150
But by default, the String object in javascript has no methods like that. But we can add one to it.
I have implemented one long time ago, and today I came up with a new implementation which is more robust.
Solution:
String.format = function () { if (arguments.length <= 0) { return ""; } else { var format = arguments[0]; var args = arguments; var s = format.replace(/(?:[^{]|^|\b|)(?:{{)*(?:{(\d+)}){1}(?:}})*(?=[^}]|$|\b)/g, function (match, number) { number = parseInt(number); return typeof args[number + 1] != "undefined" ? match.replace(/{\d+}/g, args[number + 1]) : match; }); return s.replace(/{{/g, "{").replace(/}}/g, "}"); } }; String.prototype.format = function () { if (arguments.length <= 0) { return this; } else { var format = this; var args = arguments; var s = format.replace(/(?:[^{]|^|\b|)(?:{{)*(?:{(\d+)}){1}(?:}})*(?=[^}]|$|\b)/g, function (match, number) { number = parseInt(number); return typeof args[number] != "undefined" ? match.replace(/{\d+}/g, args[number]) : match; }); return s.replace(/{{/g, "{").replace(/}}/g, "}"); } };
Usage and QUnit tests:
var format = "{0}{1}{{2}}"; var s = String.format(format, "hello", "world", "nonsense"); equal(s, "helloworld{2}"); s = format.format("hello", "world", "nonsense"); equal(s, "helloworld{2}"); format = "{0}{1}{{2}}"; s = String.format(format, "hello"); equal(s, "hello{1}{2}"); s = format.format("hello"); equal(s, "hello{1}{2}"); format = "{0}{1}"; s = String.format(format, "hello", "world"); equal(s, "helloworld"); s = format.format("hello", "world"); equal(s, "helloworld"); format = "{0}{1}"; s = String.format(format, "hello", "world", "i"); equal(s, "helloworld"); s = format.format("hello", "world", "i"); equal(s, "helloworld"); format = "{{{0}}}"; s = String.format(format, "hello"); equal(s, "{hello}"); s = format.format("hello"); equal(s, "{hello}"); format = "{{{{0}}}}"; s = String.format(format, "hello"); equal(s, "{{0}}"); s = format.format("hello"); equal(s, "{{0}}"); format = "{{{{{0}}}}}"; s = String.format(format, "hello"); equal(s, "{{hello}}"); s = format.format("hello"); equal(s, "{{hello}}");
Application Example:
Write code like this:
alert(String.format("Current Page Index: {0}, Total Pages: {1}", 10, 150));
You can run it online immediately by clicking the this link.