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;
}

兩種使用方式:this

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'}));

輸出:spa

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

相關文章
相關標籤/搜索