如何在打字稿中用 RegExp 替换字符串?

问题描述 投票:0回答:1

我想用一个变量替换一个字符串。 例如,我的字符串是 'Hello {{world}}',我想用另一个文本替换 {{world}}。要替换的字符串总是在大括号 {{}} 之间。替换为“newtext”后,我期望得到以下结果“Hello newtext”(没有大括号)。我如何在打字稿中使用 RegExp 来做到这一点?

javascript typescript regexp-replace
1个回答
0
投票

如果目标是用括号替换整个表达式,您可以执行以下操作:

const string = "Hello {{world}}";

console.log(string.replace(/{{.*}}/, "Stack overflow"));

© www.soinside.com 2019 - 2024. All rights reserved.