使用正则表达式搜索字符串,并将内容替换为数据

时间:2016-03-04 01:56:07

标签: javascript regex

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

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

    
    
    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.

    注意:

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

2 个答案:

答案 0 :(得分:1)



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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

传递给函数时的对象可以通过'object [“property”]'访问其属性。我还将你的正则表达式调整为'/ {{([^ {}] *)}} / igm',否则将其计为一个匹配'{{bird.mouth ... bird.skin}}'。

var data = {
  bird: {
    foot: 'claw',
    mouth: 'beak',
    skin: 'feathers'
  },
  dog: {
    foot: 'paw',
    mouth: 'muzzle',
    skin: 'fur'
  }
};
var html = 'A bird\'s mouth is called a {{bird.mouth}}. A dog has {{dog.skin}} where-as a bird has {{bird.skin}}.';


function getProperty(object, propertyNames) {
  var regex2 = /([^\.]+)/g;
  var results2 = regex2.exec(propertyNames);
  var ret = object;
  while (results2 != null) {
    var temp = results2[1];
    ret = ret[temp];

    results2 = regex2.exec(propertyNames);
  }

  return ret;
};

function replace(data, html) {
  var html2 = html;
  var regex = /{{([^{}]*)}}/igm;

  var results = regex.exec(html);
  while (results != null) {
    var temp0 = results[0];
    var temp1 = results[1];
    html2 = html2.replace(temp0, getProperty(data, temp1));
    results = regex.exec(html);
  }

  return html2;
}


var str = replace(data, html);
console.log(str);
document.write(str);