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.

0

3 Answers 3

4

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.