Javascript Regex(或not)用动态变量替换所有匹配项
假设我从用户输入中获取了以下字符串:Javascript Regex(或not)用动态变量替换所有匹配项,javascript,node.js,regex,Javascript,Node.js,Regex,假设我从用户输入中获取了以下字符串: The @@firstvar@@ went to the @@secondvar@@ with the @@thirdvar@@. 其中firstvar、secondvar和thirdvar的值也都来自用户输入,所以在运行之前它们是未知的 有没有办法用相应的缓存变量替换@集合之间的所有匹配项 例如,假设我缓存了这些值: cache[firstvar] = "dog" cache[secondvar] = "river" cache[thirdvar] =
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.
我尝试过正则表达式替换,但无法确定替换是动态的 可以使用函数作为中的第二个参数来替换它们 常量缓存={firstvar:dog,secondvar:river,thirdvar:cat}, text=第一个变量与第三个变量一起转到第二个变量。, regex=/@.@?@/g;
console.log text.replaceregex,_match,group1=>cache[group1];您可能会使用命名的正则表达式组。我不明白你的用户输入是怎么发生的。。。你是说当狗和猫一起去河边时,用户可以输入整个字符串吗。不知道那句话会是什么样子?