3

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

1

1 Answer 1

1

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'}) );
Sign up to request clarification or add additional context in comments.

3 Comments

@biziclop: That micro-templating stuff is pretty nice but not usable under 'use strict'; conditions since it uses with.
abesto: That certainly works but seems to violate the principle of Don't Repeat Yourself.
@ChristopherWeiss: only if the parameter is built in place like this. In a good number of cases it'll be available in a pre-existing object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.