假设我从用户输入中获取了以下字符串:
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]) );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句