String formatting for Javascript

Today, I was asked by a C# developer if Javascript has any string formatting functions comparable to the String.Format() method in C#.

I thought about it for a few minutes, going over the possibilities of regular expressions in my head, but finally settled on giving him a simple extension to Javascript's String object.

String.prototype.format = function () {
	var str = this.toString();
	if (arguments.length == 0) return str;
	for (var i=0; i<arguments.length; i++) {
		str = str.replace('{'+i+'}', arguments[i]);
	}
	return str;
}


This simple function gives your Javascript strings the exact same formatting ability they would have in C#.

Test it out for yourself:
var s = 'Hello, {0}, I am {1}, and I am {2} to meet you.';
alert (s.format('foo','bar','baz'));
comments powered by Disqus