JavaScript equivalent to printf/String.Format

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

    jsxt, Zippo

    This option fits better.

    String.prototype.format = function() {
        var formatted = this;
        for (var i = 0; i < arguments.length; i++) {
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
            formatted = formatted.replace(regexp, arguments[i]);
        }
        return formatted;
    };
    

    With this option I can replace strings like these:

    'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
    

    With your code the second {0} wouldn't be replaced. ;)

提交回复
热议问题