Interpolate Function Need
I need an javascript function that can do interpolate like the one for prototype js framework. Anyone have an interpolate function that is not depend on prototype? Jquery is welcom
Solution 1:
Depending on your needs, something like this might work:
String.prototype.interpolate = function(valueMap){
returnthis.replace(/\{([^}]+)\}/g, function(dummy, v){
return valueMap[v];
});
};
Usage:
varparams = {
"speed":"slow",
"color":"purple",
"animal":"frog"
};
var template = "The {speed} {color} fox jumps over the lazy {animal}.";
alert(template.interpolate(params));
//alerts://"The slow purple fox jumps over the lazy frog."
This will provide basic interpolation for {named}
items wrapped in braces in your string.
Note: this is a basic implementation and shouldn't be used in cases where the string or parameters are not secure (e.g. if you were to build up a SQL statement or something)
Solution 2:
If you don't care about security (eval()
is not a good thing in serious code):
evalfun = function (x) {
returneval(x);
};
String.prototype.interpolate = function (fn) {
returnthis.replace( /\{([^}]+)\}/g,
function ( dummy, v ) {
returnfn( v );
}
);
};
var world = "room""hello {world}".interpolate(evalfun);
Post a Comment for "Interpolate Function Need"