sprintf() for JavaScript that behaves like Python's format (%)?

23,642

Solution 1

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

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

Solution 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

Solution 3

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>
Share:
23,642

Related videos on Youtube

Amandasaurus
Author by

Amandasaurus

I'm a Linux user

Updated on February 12, 2020

Comments

  • Amandasaurus
    Amandasaurus about 4 years

    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.

Related