javascript - 正则表达式替换大括号内的特定单词

标签 javascript regex

Hello

{#if wordToReplace}
 World
{/if}

{#each wordToReplace as item}
{item.name}
{/item}

我想将“wordToReplace”替换为“REPLACED”(在大括号内),这样它就变成了

Hello

{#if REPLACED}
 World
{/if}

{#each REPLACED as item}
{item.name}
{/item}

我怎样才能用正则表达式做到这一点?

最佳答案

您可以尝试搜索正则表达式模式:

\{(.*?)\bwordToReplace\b(.*?)\}

然后替换为:

{$1 REPLACED $2}

var input = "Hello\n\n{#if wordToReplace}\n World\n{/if}\n\n{#each wordToReplace as item}\n{item.name}\n{/item}";
var output = input.replace(/\{(.*?)\bwordToReplace\b(.*?)\}/g, "{$1REPLACED$2}");
console.log(input);
console.log(output);

此处使用的正则表达式模式只是将搜索词两侧的所有内容覆盖在两个单独的捕获组中,然后在替换中重用这些相同的捕获组。

关于javascript - 正则表达式替换大括号内的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61243065/

相关文章:

javascript - 编辑 Google 图表类别过滤器

javascript - client.startTyping 不是一个函数(Discord.JS)

php - 有关 str_replace() 的帮助

javascript - 使用 Javascript 验证正则表达式

c++ - C++错误中使用正则表达式的问题括号表达式中的范围无效

javascript - AngularJS 包含基于当前路由的脚本

javascript - 如何在 Angular 4 中使用备用运算符将​​对象推到特定长度

javascript - 如何使用正则表达式限制数字?

mysql - 为什么我不能在 mysql 中使用 join 和正则表达式?

javascript - Angular : How to enable a text box if other text box input is valid