Oh yes ... the holy grail of interpolating javascript variables ... In fact, you can pass the local area around using dark magic as follows:
String.prototype.format = function(_eval) { return this.replace(/{(.+?)}/g, function($0, $1) { return _eval($1); }) }; function foo() { var a = 123, b = 456; s = "a is {a} and a+b={a+b}".format(function(x) {return eval(x)}) console.log(s)
I'm afraid there is no way to make the format call less verbose.
And here is the version that requires explicit transfer of visibility, but still allows arbitrary expressions in {...} 's:
String.prototype.format2 = function(scope) { eval(Object.keys(scope).map( function(x) { return "var " + x + "=scope." + x }).join(";")); return this.replace(/{(.+?)}/g, function($0, $1) { return eval($1); }) }; function foo() { var a = 123, b = 456; s = "a is {a} and a+b={a+b}".format2({a:a, b:b}) console.log(s)
You should not understand this.
georg
source share