gpt4 book ai didi

javascript - 正则表达式(或不)用动态变量替换所有匹配项

转载 作者:行者123 更新时间:2023-12-02 23:07:59 24 4
gpt4 key购买 nike

假设我从用户输入中获取了以下字符串:

The @@firstvar@@ went to the @@secondvar@@ with the @@thirdvar@@.

其中值“firstvar”、“secondvar”和“thirdvar”也都来自用户输入,因此它们在运行时之前是未知的。

有没有办法用相应的缓存变量替换“@@”组之间的所有匹配项?

假设我缓存了这些值:

cache[firstvar] = "dog"
cache[secondvar] = "river"
cache[thirdvar] = "cat"

我希望最终的输出字符串是:

The dog went to the river with the cat. 

我尝试过正则表达式替换,但无法弄清楚当替换是这样动态时。

最佳答案

您可以通过使用函数作为 String.prototype.replace() 中的第二个参数来替换它们.

const cache = { firstvar: "dog", secondvar: "river", thirdvar: "cat" },
text = "The @@firstvar@@ went to the @@secondvar@@ with the @@thirdvar@@.",
regex = /@@(.*?)@@/g;

console.log( text.replace(regex, (_match, group1) => cache[group1]) );

关于javascript - 正则表达式(或不)用动态变量替换所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57502485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com