首页 > 编程语言 > 详细

javascript 之string.format

时间:2014-08-02 01:36:33      阅读:411      评论:0      收藏:0      [点我收藏+]
function(){
    ‘use strict‘;

    if(String.prototype.format)
        return;
        
    String.prototype.format = function(args){
    
        var _dict = typeof(args) == ‘object‘ ? args : arguments;
        
        return this.replace(/{([^{}]+)}/g,function(s,n){
            return _dict[n]===undefined?s:_dict[n];
        });
    
    };
    
})();

 

useage:

var str = ‘{name} is {age} years old.‘;
str.format({name:‘Tom‘,age:25});//”Tom is 25 years old.”
str = ‘{0} is {1} years old.‘;
str.format(‘Jerry‘,15);//”Jerry is 15 years old.”
str.format([‘Bill‘,10]);//"Bill is 10 years old."
 

javascript 之string.format,布布扣,bubuko.com

javascript 之string.format

原文:http://www.cnblogs.com/fly-could/p/3886033.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!