interpolate function need

被刻印的时光 ゝ 提交于 2021-01-28 01:53:30

问题


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 welcome. Thanks.


回答1:


Depending on your needs, something like this might work:

String.prototype.interpolate = function(valueMap){
  return this.replace(/\{([^}]+)\}/g, function(dummy, v){
    return valueMap[v];
  });
};

Usage:

var params = {
  "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)




回答2:


If you don't care about security (eval() is not a good thing in serious code):

evalfun = function (x) {
  return eval(x);
};

String.prototype.interpolate = function (fn) {
  return this.replace( /\{([^}]+)\}/g,
    function ( dummy, v ) {
      return fn( v );
    }
  );
};

var world = "room"
"hello {world}".interpolate(evalfun);


来源:https://stackoverflow.com/questions/5357121/interpolate-function-need

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!