JavaScript equivalent to printf/String.Format

前端 未结 30 2504
囚心锁ツ
囚心锁ツ 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:03

    Adding to zippoxer's answer, I use this function:

    String.prototype.format = function () {
        var a = this, b;
        for (b in arguments) {
            a = a.replace(/%[a-z]/, arguments[b]);
        }
        return a; // Make chainable
    };
    
    var s = 'Hello %s The magic number is %d.';
    s.format('world!', 12); // Hello World! The magic number is 12.
    

    I also have a non-prototype version which I use more often for its Java-like syntax:

    function format() {
        var a, b, c;
        a = arguments[0];
        b = [];
        for(c = 1; c < arguments.length; c++){
            b.push(arguments[c]);
        }
        for (c in b) {
            a = a.replace(/%[a-z]/, b[c]);
        }
        return a;
    }
    format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats
    

    ES 2015 update

    All the cool new stuff in ES 2015 makes this a lot easier:

    function format(fmt, ...args){
        return fmt
            .split("%%")
            .reduce((aggregate, chunk, i) =>
                aggregate + chunk + (args[i] || ""), "");
    }
    
    format("Hello %%! I ate %% apples today.", "World", 44);
    // "Hello World, I ate 44 apples today."
    

    I figured that since this, like the older ones, doesn't actually parse the letters, it might as well just use a single token %%. This has the benefit of being obvious and not making it difficult to use a single %. However, if you need %% for some reason, you would need to replace it with itself:

    format("I love percentage signs! %%", "%%");
    // "I love percentage signs! %%"
    

提交回复
热议问题