Thursday, June 21, 2007

String.format function in Javascript

Javascript String Formatting function (just like in C#);


String.format = function() {
if(arguments.length == 0)
return null;
var str = arguments[0];
for(var i=1;i<arguments.length;i++) {
var re = new RegExp('\\{' + (i-1) + '\\}','gm');
str = str.replace(re, arguments[i]);
}
return str;
}
////Sample;
//var a = String.format("{0} {1}", "Hello", "World");
////Output: Hello World

1 comments:

Amaris said...

Good words.