javascript - 如何使用变量名实现字符串格式化程序

我想实现一个字符串格式化程序。我使用了像 "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;
};
  1. 有没有办法在不使用 eval 的情况下做到这一点(看起来不像)。
  2. 有没有办法给 eval 闭包以便获得作用域?我试过了 with(window)window.eval(),但这不起作用。

最佳答案

对于 var result = "This will get formatted with my {name} and {number}".format({name: "TetsujinOni", number: 1234});

p>

为什么不朝这个方向前进:

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/

相关文章:

java - 在字符串模板电子邮件中格式化日期

sql - 在 Oracle 中将时差转换为给定格式

emacs - 在 LaTeX 模式 emacs 中缩进 C 代码区域

forms - 如何在 Laravel 中处理日期输入

vim - 使用 Vim,是否有更有效的方法来根据这个最佳实践来格式化 LaTeX 段落?

python - 在没有空格或换行符的python中打印变量

c# - DataGridViewCheckBoxColumn : FormatException

formatting - JSON.Net 将 XML 序列化为 JSON 驼峰式案例

formatting - Gnuplot 平滑置信区间线而不是误差线

ios - iPhone : How to get number from string with