JavaScript equivalent to printf/String.Format

前端 未结 30 3261
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

30条回答
  •  离开以前
    2020-11-21 05:10

    I'm surprised no one used reduce, this is a native concise and powerful JavaScript function.

    ES6 (EcmaScript2015)

    String.prototype.format = function() {
      return [...arguments].reduce((p,c) => p.replace(/%s/,c), this);
    };
    
    console.log('Is that a %s or a %s?... No, it\'s %s!'.format('plane', 'bird', 'SOman'));

    < ES6

    function interpolate(theString, argumentArray) {
        var regex = /%s/;
        var _r=function(p,c){return p.replace(regex,c);}
        return argumentArray.reduce(_r, theString);
    }
    
    interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"
    

    How it works:

    reduce applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    var _r= function(p,c){return p.replace(/%s/,c)};
    
    console.log(
      ["a", "b", "c"].reduce(_r, "[%s], [%s] and [%s]") + '\n',
      [1, 2, 3].reduce(_r, "%s+%s=%s") + '\n',
      ["cool", 1337, "stuff"].reduce(_r, "%s %s %s")
    );

提交回复
热议问题