Archive for March, 2009

March 10th, 2009 at 5:29 pm

JavaScript printf()

The printf function is known in many programming languages. It allows to replace a certain pattern in a string with other strings.

Here’s a little printf() for JavaScript. It can’t do very much; in fact, it only can replace the placeholder %s multiple times.

var printf = function(string)
{
	if (arguments.length < 2) { return string; }
		for (var i=1; i<arguments.length; i++)
		{ string = string.replace(/%s/, arguments[i]); }
	return string;
}

Although it’s not too advanced, it can be helpful if want to produce something as a pagination:

var pagination = '';
var numpages = 5;
 
for (var page=1; page<=numpages; page++)
{
	pagination += printf('Page %s of %s', page, numpages);
}