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/