[JS] 如何自定义字符串格式化输出

在其他语言中十分常见的字符串格式化输出,居然在 Javascript 中不见踪影,于是决定自己实现该方法,以下就是个人编写的最简洁实现:

String.prototype.format = function(){
    var args = arguments;
    return this.replace(/{(d+)}/gm, function(ms, p1){return typeof(args[p1]) == 'undefined' ? ms : args[p1]});
}

应用示例:

>>> "{0} is not {1}".format("Linux", "Unix")
"Linux is not Unix"
原文地址:https://www.cnblogs.com/ifantastic/p/3512454.html