实现
JAVASCRIPTString.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, 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;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
调用
对包含占位符的字符串调用format
方法,传入一个要替换的参数数组。
占位符"{-1}"固定返回"{",占位符"{-2}"固定返回"}"。
JAVASCRIPTvar str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
console.log(str);
输出She sells seashells by the seashore. {^_^}