我有一个包含要替换为JSON对象的值的字符串。我已经用{{*}}指定了这些值(即-{{bird.foot}})。我已经写了一些JavaScript,但是遇到了麻烦:


仅选择每个{{}}中的项目。我正在选择一切
从字符串中的第一组括号到最后一组
字符串中的括号。
将括号内的每个项目替换为data变量中的相应值




var data = {
        bird: {
            foot: 'claw',
            mouth: 'beak',
            skin: 'feathers'
        },
        dog: {
            foot: 'paw',
            mouth:'muzzle',
            skin: 'fir'
        }
    },
    html = 'A bird\'s mouth is called a {{bird.mouth}}. A dog has {{dog.skin}} where-as a bird has {{bird.skin}}.',
    regex = /({{)(.)*(}})/igm,
    results = html.match(regex);

console.log(results);





运行上面的代码片段将输出带有一个元素的数组:["{{bird.mouth}}. A dog has {{dog.skin}} where-as a bird has {{bird.skin}}"]。我期望包含三个元素的数组:[{{bird.mouth}}, {{dog.skin}}, {{bird.skin}}]

最终,我希望输出结果:A bird\'s mouth is called a break. A dog has fur where-as a bird has feathers.

笔记:


属性将不按字母顺序排列
我无法为我的项目使用模板库。我的项目涉及通过Optimizely(AB测试平台)将代码注入到页面上。我只能访问自己编写的JavaScript。

最佳答案

var data = {
        bird: {
            foot: 'claw',
            mouth: 'beak',
            skin: 'feathers'
        },
        dog: {
            foot: 'paw',
            mouth:'muzzle',
            skin: 'fir'
        }
    },
    html = 'A bird\'s mouth is called a {{bird.mouth}}. A dog has {{dog.skin}} where-as a bird has {{bird.skin}}.',
    regex = /{{([^]*?)}}/g,
    results = html.match(regex);


// clean way, only for prop.prop.prop
var result = html.replace(regex, function(_, e) {
  var down = e.split(/\./);
  var datum = data;
  while (down.length) {
    datum = datum[down.shift()];
  }
  return datum;
});
console.log(result);

//evil way, more flexible, less safe, slower
var result = html.replace(regex, function(_, e) {
  return eval("data." + e);
});
console.log(result);

<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

07-24 09:43
查看更多