首页 > 解决方案 > 如何修复要接收替换的数据的大小写在字符串中搜索指定值(appleJam)或正则表达式

问题描述

> Blockquote
my expected output is:
"hello Alex, aewgtfrgtr,
"hello Alexx, aewgtfrgtrr, 
"hello Alexxx, aewgtfrgtrrr,ewgtf, 
"Hello World,"

我将模板和数据传递给一个函数,然后使用enter code herematch 查找字符串以查找与正则表达式匹配的字符串,并将匹配项作为 Array 对象返回。然后使用 replace 在字符串中搜索指定值(appleJam ) 或正则表达式,并返回替换指定值的新字符串。

function test(template, data) {

  var jam = template;
  let appleJam = jam.match(/{{.+?}}/g);//{{???}}array
  let peachJam = Object.values(data);

      let toast = jam.replace(appleJam, peachJam);
        console.log(toast);
        return toast;

} //function
    
    test("hello {{name}}, {{erio9tr8dhygtj9eryh}}", {
      name: "Alex",
      erio9tr8dhygtj9eryh: "aewgtfrgtr",
    }); // hello Alex, aewgtfrgtr
    
    test("hello {{rsgwrg}}, {{eabernab}}", {
      rsgwrg: "Alexx",
      eabernab: "aewgtfrgtrr",
    }); // hello Alex, aewgtfrgtr
    
    test("hello {{a4trjhtr}}, {{h5yj6t5n}} {{wegr}}", {
      a4trjhtr: "Alexxx",
      h5yj6t5n: "aewgtfrgtrrr",
      wegr: "ewgtf",
    }); // hello Alex, aewgtfrgtr ewgtf
    
    
    test("Hello{{item}}", {
      item: " World",
    }); // Hello World

标签: regexreplace

解决方案


所示函数仅替换第一个匹配项appleJam[0]。如果我们迭代,我们可以替换更多匹配data

function test(template, data)
{
    for ([key, value] of Object.entries(data))
        template = template.replace("{{"+key+"}}", value)
    return template;
}

如果一个键可以重复出现,我们使用replaceAll.


推荐阅读