在Javascript里通过原型扩展和正则表达式实现类似于C#里的String.Format方法.
方法实现:
String.prototype.format = function (args) {
var str = this;
return str.replace(new RegExp("{-?[0-9]+}", "g"), function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
var str = this;
return str.replace(new RegExp("{-?[0-9]+}", "g"), function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
使用如下:
var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);//out put: She sells seashells by the seashore. {^_^}
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);//out put: She sells seashells by the seashore. {^_^}