Tuesday, April 21, 2009

Variable interpolation in javascript strings

I came across this fairly old attempt at making variable interpolation work in javascript.

The conclusion was that it could only be made to work with object properties or global variables.

But as it turns out, we can make interpolation of local variables work:

var expand = function(string) {
 return '"' + string.replace(/"/g, '\\"').replace(/\{/g, '"+').replace(/\}/g, '+"') + '"';
}
new function() {
 var hello = "hello world";
 alert(eval(expand('say "{hello}"')))

 var quote = '"';
 alert(eval(expand("a quote looks like this: {quote}")))
}

I'm not checking for escape sequences for curly braces, but adding support for that shouldn't be too hard.

No comments:

Post a Comment