regex - 如何修复要接收替换的数据的大小写在字符串中搜索指定值(appleJam)或正则表达式
问题描述
> Blockquote
my expected output is:
"hello Alex, aewgtfrgtr,
"hello Alexx, aewgtfrgtrr,
"hello Alexxx, aewgtfrgtrrr,ewgtf,
"Hello World,"
我将模板和数据传递给一个函数,然后使用enter code here
match 查找字符串以查找与正则表达式匹配的字符串,并将匹配项作为 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
解决方案
所示函数仅替换第一个匹配项appleJam[0]
。如果我们迭代,我们可以替换更多匹配data
:
function test(template, data)
{
for ([key, value] of Object.entries(data))
template = template.replace("{{"+key+"}}", value)
return template;
}
如果一个键可以重复出现,我们使用replaceAll
.
推荐阅读
- c# - 我已经编写了文件是否存在的逻辑。(读取excel中的文件名并检查文件是否存在于另一个文件夹中)
- python - 如何更改 OpenCv 中高斯自适应阈值的权重?
- ruby-on-rails - Unicorn (4.9.0) + Rails (2.2.2) 总是给我相同的 session_id - 你知道如何解决这个问题吗?
- intellij-idea - 无法执行目标 net.alchim31.maven:scala-maven-plugin:3.2.0:compile (scala-compile)
- javascript - node.js 使用两个具有不同端口的套接字
- identityserver4 - Identity Server 4 注册后自动登录不起作用
- java - Firebase 数据库从子 android 访问节点
- c++ - 我怎样才能使这个程序显示键入的数字与数字的值一样多次?
- java - CompletableFuture - 异步任务执行是错误的?
- java - 在 JavaFx 中禁用键盘快捷键