我想实现一个字符串格式化程序。我使用了像 "the quick, brown {0} jumps over the lazy {1}"
这样的格式化程序,您可以在其中传入参数,其基数位置用于替换大括号整数。
我希望能够做一些更像 "the quick, brown {animal1} jumps over the lazy {animal2}"
之类的东西,其中 animal1 和 animal2 是变量并且被简单地评估。我实现了以下方法,但后来意识到 eval 不起作用,因为它不使用相同的范围。
String.prototype.format = function() {
reg = new RegExp("{([^{}]+)}", "g");
var m;
var s = this;
while ((m = reg.exec(s)) !== null) {
s = s.replace(m[0], eval(m[1]));
}
return s;
};
with(window)
和 window.eval()
,但这不起作用。最佳答案
对于 var result = "This will get formatted with my {name} and {number}".format({name: "TetsujinOni", number: 1234});
为什么不朝这个方向前进:
String.prototype.format = function(scope) {
reg = new RegExp("{([^{}]+)}", "g");
var m;
var s = this;
while ((m = reg.exec(s)) !== null) {
s = s.replace(m[0], scope[m[1]]);
}
return s;
};
https://stackoverflow.com/questions/19254362/