Trying to avoid javascript eval ()

Let's say I want to add an interpolation variable to String like so:

String.prototype.interpolate = function() {
    return this.replace(/{(\S+?)}/g, function(match, $1) {return eval($1);});


If all my variables are global or local, I could replace eval($1)

with this[$1]

. However, if I have something like var name = {first: 'Joe', last: 'Blogs'};

that, it this[$1]

won't work for interpolation "Hello, {name.first} {name.last}!".interpolate()

. Can I use instead eval()

? If I expect these variables to come from an unreliable source, then I really cannot use eval()



source to share

1 answer

If you don't want to use the template engine you created earlier, I would suggest making the data for interpolation 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'}) );




All Articles