javascript 之string.format

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,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。