Let's say I want to add variable interpolation to String like so:
String.prototype.interpolate = function() {
return this.replace(/{(\S+?)}/g, function(match, $1) {return eval($1);});
}
If all of my variables are global or local then I could replace eval($1) with this[$1]. However if I've got something like var name = {first: 'Joe', last: 'Blogs'}; then this[$1] will not work to interpolate "Hello, {name.first} {name.last}!".interpolate(). Is there anything I could use in place of eval()? If I'm expecting those variables to come from an untrusted source then I really cannot use eval().
If you don't want to use a pre-existing template engine, I'd suggest making the data to interpolate explicit:
String.prototype.interpolate = function(data) {
return this.replace(/{(\S+?)}/g, function(match, $1) {return data[$1];});
}
console.log( '{a} is better than {b}'.interpolate({'a':'explicit', 'b':'implicit'}) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With