4

I need a JavaScript function (or jQuery plugin) for printf/sprintf. It needs to support named arguments ("%(foo)s") and padding ("%02d"), i.e. the following format string should work:

"%(amount)s.%(subunits)02d"

It only needs to support s and d, I don't care about all the other format strings (e.g. f, x, etc.). I don't need padding for strings/s, just d, I only need simple padding for d, e.g. %2d, %3d, %04d, etc.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248

3 Answers3

4

A previous question "Javascript printf/string.format" has some good information.

Also, dive.into.javascript() has a page about sprintf().

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
2

Here one function

var sprintf = function(str) {
  var args = arguments,
    flag = true,
    i = 1;

  str = str.replace(/%s/g, function() {
    var arg = args[i++];

    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
};

$(document).ready(function() {

  var msg = 'the department';

  $('#txt').html(sprintf('<span>Teamwork in </span> <strong>%s</strong>', msg));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<center id="txt"></center>
Tunaki
  • 132,869
  • 46
  • 340
  • 423
2

The PHPJS project has implemented a lot of PHP's functionality in Javascript. I can't imagine why they'd want to do that, but the fact remains that they have produced a sprintf() implementation which should satisfy your needs (or at least come close).

Code for it can be found here: http://phpjs.org/functions/sprintf

Spudley
  • 166,037
  • 39
  • 233
  • 307