String.Format
method from .NET Framework has multiple signatures. The one I like the most uses params keyword in its prototype, i.e.:
public static string Format(
string format,
params Object[] args
)
Using this version, you can not only pass variable number of arguments to it but also an array argument.
Because I like the straightforward solution provided by Jeremy, I'd like to extend it a bit:
var StringHelpers = {
format: function(format, args) {
var i;
if (args instanceof Array) {
for (i = 0; i < args.length; i++) {
format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), args[i]);
}
return format;
}
for (i = 0; i < arguments.length - 1; i++) {
format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i + 1]);
}
return format;
}
};
Now you can use your JavaScript version of String.Format
in the following manners:
StringHelpers.format("{0}{1}", "a", "b")
and
StringHelpers.format("{0}{1}", ["a", "b"])