String.interpolate()
Here’s a string prototype that allows you to interpolate variables into a string (ruby style). All you have to do is create your template and call interpolate on it ( with an object literal as a parameter for the vars to interpolate ).
Example:
var template = "The #{foxAdj}, #{foxAdj2} fox jumped over the #{dogAdj} dog.";
// alert "The quick, brown fox jumps over the lazy dog."
alert( template.interpolate( { foxAdj: 'quick', foxAdj2: 'brown', dogAdj: 'lazy' } ) );
You don’t have to use single variables within the template string either. Check these out:
var template = "#{var1} + #{var2} = #{var1 + var2}.";
alert( template.interpolate({ var1: 1, var2: 2 }) ); //prints "1 + 1 = 2"
var template = "Hello #{name()}!";
alert( template.interpolate({ name: function() { return "World"; } } ) ); // alerts "Hello World!"
And heres the code:
String.prototype.interpolate = function() {
for ( i in arguments[0] ) {
eval( i + ' = "' + arguments[0][i] + '"' );
}
return this.replace( /#\{.*?\}/g, function(match) {
return eval( match.replace( /^#\{|\}$/g , '') );
});
};
If anybody can think of a way to do this without eval, I would love to see it. Comments are welcome.
Comment from Matma Rex
Time: June 27, 2008, 8:34 am
My version, much simplier (just strings, but would you ever need more?), but working without eval:
String.prototype.interpolate = function(obj)
{
str=this
for(i in obj)
{
str=str.replace(’#{’+i+’}',obj[i])
}
return str
}