简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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