用对象中的值替换字符串

时间:2015-09-23 15:59:58

标签: javascript

我正在开发一个功能来搜索对象属性,并替换“手柄栏”。字符串中的值。

问题

如何更改以下代码以将{{phones.primary}}替换为其值。

function template(content, values) {

    for(prop in values) {

        content = content.replace('{{' + prop + '}}', values[prop]);

    }

    return content;
}


alert(template('Hello {{name}}. Your primary number is {{phones.primary}}', {

    name: 'Mickey Mouse',
    phones: {
        primary: '123-123-1234'
    }

}));

3 个答案:

答案 0 :(得分:4)

不是循环遍历对象并检查字符串中是否存在该键/值对,而是使用正则表达式来提取所有{{name}}字符串。然后,您可以使用回调来搜索对象以获取所需的值。

function template(content, values) {
    // This will search the string for `{{name}}`
    // The 1st param to the callback is the entire match (`{{name}}`)
    // and the 2nd is the first capture group (`name`).
    return content.replace(/{{(.+?)}}/g, function(match, prop){
        // Convert keys like `phones.primary` into an array of paths
        // then "reduce" that array into one value.
        // This lets us go through the object and drill down
        // until we get the value we want.
        return prop.split('.').reduce(function(obj, key){
            return obj[key];
        }, values);
    });
}

答案 1 :(得分:2)

出现此问题是因为您无法访问对象中的属性。你可以使用正则表达式匹配所有把手{{}},然后使用另一个函数向下钻取它是否是一个对象:

function evaluateProperty(values, path) {
    var parts = path.split(".");
    var result = values;

    parts.forEach(function(part) {
        result = result[part];
    });

    return result;
}

function template(content, values) {

    content = content.replace(/\{\{(.*?)\}\}/g, function(match, a) {
        return evaluateProperty(values, a);
    });

    return content;
}


alert(template('Hello {{name}}. Your primary number is {{phones.primary}}', {
    name: 'Mickey Mouse',
    phones: {
        primary: '123-123-1234'
    }
}));

答案 2 :(得分:0)

我有类似的东西。它需要一个模板化的字符串并返回一个函数。该函数接受一个对象(包括像你这样的树对象)并返回带有填充数据的原始字符串。

它使用underscore

/*
      given a template string, returns a function that can be passed data and will return the populated string
     */
     function compile_template(str)
      {
          var replace_in = function(rep, pre, prop_name, val)
          {
              if(typeof val == "object")
              {
                  if(rep.search(new RegExp("\\{\\{" + pre + prop_name , "g")) >= 0)
                  {
                    _.each(val, function(v, k){ rep = replace_in(rep, pre + prop_name + ".", k, v); });
                  }
                  return rep;
              }
              else
              {
                  return rep.replace(new RegExp("\\{\\{" + pre + prop_name + "\\}\\}", "g"), val);
              }
          };
        return  function(obj)
                {
                  var representation = str;    
                  _.each(obj, function(v, k)
                  {
                      representation = replace_in(representation, "", k, v);
                  });
                  return clean_representation(representation);
                };
      }
     
     
     /*
       removes any unmatched mustache variables from the string.
     */
     function clean_representation(str)
     {
         return str.replace(/\{\{[^}]*\}\}/g, "");
     }

     //example:
     //var mytemplate_f = compile_template("Hello {{name}}. Your primary number is {{phones.primary}}");
     //console.log(mytemplate_f({name:"Mickey Mouse", phones:{primary:"555-5555"}})); => "Hello Mickey Mouse. Your primary number is 555-5555"
<script src="http://underscorejs.org/underscore-min.js"></script>