Client-side JavaScript sprintf equivalent

I know I console.log

support at least some of the core functionality printf

from C via messing around, but I was curious how to use the implementation console.log

to create something similar to sprintf

, I know you can't just use .bind

or .apply

since it console.log

doesn't actually return line, so is there a way to get around this?

If this is actually not possible, is there some other little-known built-in implementation that is only a few lines of code from reaching sprintf

in JavaScript?

For those who don't know what exactly is sprintf

exactly, here is some documentation from the tutorial point . The usage example I'm looking for is below:

var string1 = sprintf("Hello, %s!", "world");
var string2 = sprintf("The answer to everything is %d.", 42);

      

+3


source to share


2 answers


Keep it simple

var sprintf = (str, ...argv) => !argv.length ? str : 
    sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

      

Since Javascript handles data types automatically, there is no need for type parameters.

If you need to fill in, "15".padStart(5,"0")

= ("00000"+15).slice(-5)

= "00015"

.



Using

var sprintf = (str, ...argv) => !argv.length ? str : 
    sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

alert(sprintf("Success after $ clicks ($ seconds).", 15, 4.569));
sprintf.token = "_";
alert(sprintf("Failure after _ clicks (_ seconds).", 5, 1.569));

sprintf.token = "%";
var a = "%<br>%<br>%";
var b = sprintf("% plus % is %", 0, 1, 0 + 1);
var c = sprintf("Hello, %!", "world");
var d = sprintf("The answer to everything is %.", 42);
document.write(sprintf(a,b,c,d));
      

Run code


+2


source


Try to use , eval

.replace



var sprintf = function sprintf() {
  // arguments
  var args = Array.prototype.slice.call(arguments)
    // parameters for string
  , n = args.slice(1, -1)
    // string
  , text = args[0]
    // check for `Number`
  , _res = isNaN(parseInt(args[args.length - 1])) 
             ? args[args.length - 1] 
               // alternatively, if string passed
               // as last argument to `sprintf`,
               // `eval(args[args.length - 1])`
             : Number(args[args.length - 1]) 
    // array of replacement values
  , arr = n.concat(_res)
    // `res`: `text`
  , res = text;
  // loop `arr` items
  for (var i = 0; i < arr.length; i++) {
    // replace formatted characters within `res` with `arr` at index `i`
    res = res.replace(/%d|%s/, arr[i])
  }
  // return string `res`
  return res
};

document.write(sprintf("%d plus %d is %d", 0, 1, 0 + 1) 
               + "<br>" 
               + sprintf("Hello, %s!", "world") 
               + "<br>" 
               + sprintf("The answer to everything is %d.", 42)
              );
      

Run code


+2


source







All Articles