Christopher Weiss
Christopher Weiss

Reputation: 755

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

Upvotes: 3

Views: 310

Answers (1)

abesto
abesto

Reputation: 2351

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'}) );

Upvotes: 1

Related Questions