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
  • 35,848
  • 27
  • 79
  • 88
Amandasaurus
  • 54,108
  • 68
  • 182
  • 239

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
diEcho
  • 52,196
  • 40
  • 166
  • 239
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
  • 125,519
  • 44
  • 317
  • 399
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
  • 161,975
  • 39
  • 229
  • 303