Copied to clipboard
 
 
 
 

sprintf() for Javascript

For anyone familiar with C, C++, Perl, PHP, bash, etc, you are also familiar with the printf() method. printf() allows characters in the format string to be copied to the functions outpt, or stdout, with the other parameters being rendered into the resulting text at points marked by format specifiers, which are typically introduced by a % character.

Where am I going with this lecture? Well, the sprintf() method is identicle to the printf() method with one exception. sprintf() saves the value as a string, or variable. Unfortunately, Javascript does not have a similar method. Consistancy is nice when it comes to programming environments even though not all programming languages are the same.

In any case, here's a modular sprintf() method. We didn't write the method but in researching sprintf() for Javascript, the results were located deep within Google's massive index. Because it is licensed under the GNU General Public License, here is a repost. You can download the original source code here.

As a courtesy, you can copy the code to your clipboard by clicking inside the code box. Or you can download the file: gzip zip uncompressed.

Code: string sprintf(string format[mixed arg1[, mixed arg2[,...]]])
  1. /*      sprintf() for JavaScript v.0.4
  2.        
  3.         Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
  4.         Thanks to David Baird (unit test and patch).
  5.        
  6.         This program is free software; you can redistribute it and/or modify it under
  7.         the terms of the GNU General Public License as published by the Free Software
  8.         Foundation; either version 2 of the License, or (at your option) any later
  9.         version.
  10.        
  11.         This program is distributed in the hope that it will be useful, but WITHOUT
  12.         ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13.         FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  14.         details.
  15.        
  16.         You should have received a copy of the GNU General Public License along with
  17.         this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  18.         Place, Suite 330, Boston, MA 02111-1307 USA
  19. -------------------------------------------------------------------------------- */
  20. function sprintf () {
  21.         var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  22.         while (f) {
  23.                 if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
  24.                 else if (m = /^\x25{2}/.exec(f)) o.push('%');
  25.                 else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
  26.                         if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) { throw("Too few arguments."); }
  27.                         if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) { throw("Expecting number but found " + typeof(a)); }
  28.                        
  29.                         switch (m[7]) {
  30.                                 case 'b': a = a.toString(2); break;
  31.                                 case 'c': a = String.fromCharCode(a); break;
  32.                                 case 'd': a = parseInt(a); break;
  33.                                 case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
  34.                                 case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
  35.                                 case 'o': a = a.toString(8); break;
  36.                                 case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
  37.                                 case 'u': a = Math.abs(a); break;
  38.                                 case 'x': a = a.toString(16); break;
  39.                                 case 'X': a = a.toString(16).toUpperCase(); break;
  40.                         }
  41.                        
  42.                         a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
  43.                         c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
  44.                         x = m[5] - String(a).length;
  45.                         p = m[5] ? str_repeat(c, x) : '';
  46.                         o.push(m[4] ? a + p : p + a);
  47.                 }
  48.                 else throw ("Huh ?!");
  49.                 f = f.substring(m[0].length);
  50.         }
  51.        
  52.         return o.join('');
  53. }
  54.  
  55. function str_repeat(i,m) {
  56.         for (var o = []; m > 0; o[--m] = i); return(o.join(''));
  57. }

Back to Top