如何实现具有变量名称的字符串格式化程序

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)
  1. 有没有办法在不使用eval的情况下执行此操作(看起来不像).
  2. 有没有办法给eval提供封闭,以便获得范围?我试过 with(window)window.eval(),但没有奏效.

h2o*_*ooo 5

所有全局变量都在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的解决方案.


Tet*_*Oni 5

对于像 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)