Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to avoid javascript eval()

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().

like image 297
Christopher Weiss Avatar asked Feb 24 '26 16:02

Christopher Weiss


1 Answers

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'}) );
like image 58
abesto Avatar answered Feb 26 '26 04:02

abesto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!