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.

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

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

JAVASCRIPT:
  1. var pagination = '';
  2. var numpages = 5;
  3.  
  4. for (var page=1; page<=numpages; page++)
  5. {
  6.     pagination += printf('Page %s of %s', page, numpages);
  7. }

Update 08.04.09, 12:11: Found a better solution.)