简体   繁体   English

正则表达式替换花括号内的特定单词

[英]Regex replace specific word inside curly brace

Hello

{#if wordToReplace}
 World
{/if}

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

I would like to replace the "wordToReplace" to "REPLACED" (inside curly brace) so it become我想将“wordToReplace”替换为“REPLACED”(大括号内),这样它就变成了

Hello

{#if REPLACED}
 World
{/if}

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

How could I do that with regex?我怎么能用正则表达式做到这一点?

You may try searching on the regex pattern:您可以尝试搜索正则表达式模式:

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

and then replace with:然后替换为:

{$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);

The regex pattern used here just blankets all content on either side of the search term in two separate capture groups, and then reuses those same capture groups in the replacement.此处使用的正则表达式模式只是将搜索词两侧的所有内容覆盖在两个单独的捕获组中,然后在替换中重复使用这些相同的捕获组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM