就是想匹配字符串模板里面的{0},{1},...等等,例如:var str1 = "我是{0},年龄{1}";str1.format("aa", 12);之后str1为:我是aa,年龄12
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"); console.log(reg); 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"); console.log(reg); result = result.replace(reg, arguments[i]); } } } } return result; }
上面那个代码的else里面有错误,说是:Invalid regular expression: /{0}/: Nothing to repeat。
一只斗牛犬
相关分类