美文网首页
js string format

js string format

作者: jumper996 | 来源:发表于2019-05-21 18:10 被阅读0次
         /** string **/
         String.prototype.format = function(args) {
             var result = this;
             if (arguments.length > 0) {
                 if (arguments.length == 1 && typeof (args) == "object") {
                     for (var key in args) {
                         if(args[key]!=undefined){
                             var reg = new RegExp("({" + key + "})", "g");
                             result = result.replace(reg, args[key]);
                         }
                     }
                 }
                 else {
                     for (var i = 0; i < arguments.length; i++) {
                         if (arguments[i] != undefined) {
                             var reg= new RegExp("({)" + i + "(})", "g");
                             result = result.replace(reg, arguments[i]);
                         }
                     }
                 }
             }
             return result;
         }
    
     var template1="我是{0},今年{1}了";
     var result1=template1.format("loogn",22);
    
     var template2="我是{name},今年{age}了";
     var result2=template2.format({name:"loogn",age:22});
    

    相关文章

      网友评论

          本文标题:js string format

          本文链接:https://www.haomeiwen.com/subject/qxqszqtx.html