Jer*_*ter 7 javascript formatting string-formatting
我想实现一个字符串格式化程序.我已经使用了格式化程序,它采用字符串,就像"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;
};
Run Code Online (Sandbox Code Playgroud)
with(window)和window.eval(),但没有奏效.所有全局变量都在window对象中定义,因此您应该能够在没有eval的情况下执行此操作:
String.prototype.format = function(scope) {
scope = scope || window; //if no scope is defined, go with window
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;
};
Run Code Online (Sandbox Code Playgroud)
在这里,您还应该能够简单地改变window到您想要的范围.
如果变量不在全局范围内,而是在当前范围内,您可能希望阅读此内容或使用Tetsujin的解决方案.
对于像 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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |