Peter Leonov's Blog

String.interpolateJS()

22 November 2008

This helps putting a bit of JS into a plain old string. A very handy feature for all kind of language packs. Beware: no limits for JS, no sandboxind.


"Welcome to ${company}!".interpolateJS({company:'Programica'})
//=> "Welcome to Programica!"

"Your name is ${name}.".interpolateJS({name:prompt('What is your name?')})
//=> "Your name is Dima."

// tru javascript inside :)
"Your name is ${prompt('What is your name?')}.".interpolateJS({})
//=> "Your name is Dima."

"${this.interpolateJS({})}".interpolateJS({})
// too much recursion

("${another = 'another', 'Just'} ${another}"+
    " ${'tpircSavaJ'.split('').reverse().join('')}"+
    " ${[\"hacker\"] || ''},").interpolateJS({another:1})
//=> "Just another JavaScript hacker,"

Full compilation is done only once per sting as the resulting function gets cached. This is why the first call to interpolateJS() would be slower then next.

If you need the cached function by a sting use the String.prototype.interpolateJS.cache object:


var string = "${x} + 2 = ${ x + 2 } :)"
string.interpolateJS({x:2})
//=> "2 + 2 = 4 :)"

String.prototype.interpolateJS.cache[string]
//=> function ($_$h) { with ($_$h) { return x + $_$s[1] + (x + 2) + $_$s[2]; } }

Source code in liby.

Tags:
  • frontend
  • eval
  • interpolate
  • javascript
  • parsing
  • string
  • with