problem description
just want to match {0}, {1}, in the string template. Wait, for example: var str1 = "I am {0}, age {1}"; str1.format ("aa", 12); then str1: I am aa, age 12
related codes
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; iPP) {
if(arguments[i] != undefined) {
var reg = new RegExp("{" + i + "}", "g");
console.log(reg);
result = result.replace(reg, arguments[i]);
}
}
}
}
return result;
}
what result do you expect? What is the error message actually seen?
there is an error in the else of the above code, which says: Invalid regular expression: / {0} /: Nothing to repeat.