I'd like to implement a string formatter. I've used formatters that take string like "the quick, brown {0} jumps over the lazy {1}"
where you pass in parameters whose cardinal location is used to replace the braced integers.
I'd love to be able to do something more like "the quick, brown {animal1} jumps over the lazy {animal2}"
where animal1 and animal2 are variables and are simply evaluated. I got the following method implemented, but then realized that eval is not going to work because it doesn't use the same scope.
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;
};
- Is there a way to do this without using eval (doesn't seem like it).
- Is there a way to give eval the closure so it gets scope? I tried
with(window)
andwindow.eval()
, but that didn't work.