[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"

 

posted @ 2014-08-09 18:14  iFantasticMe  阅读(2609)  评论(0编辑  收藏  举报