js仿c# format 实现,格式化字符串

String.prototype.format=function(data){
    var str=this;
    if(data && typeof(data)=='object'){
        for(var item in data){
            str=str.replace('{'+item+'}',data[item]);
        }
    }else if(arguments.length>0){
        for(var i=0;i<arguments.length;i++){
            str=str.replace('{'+i+'}',arguments[i]);
        }
    }else{
        //其他
    }
    return str;
}

两种使用方式:

console.log('we are {0} , and {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}'.format('12','ff','ff','ff','ff','ff','ff','ff','ff','ff','ff','ffa'));
console.log('we are {title} , and {content} '.format({title:'abc',content:'string'}));

输出:

we are 12 , and ff ff ff ff ff ff ff ff ff ff ffa
we are abc , and string

posted @ 2016-02-24 15:42  冰vs焰  阅读(268)  评论(0编辑  收藏  举报