Jemika Negara
Jemika Negara

Reputation: 64

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?

Upvotes: 1

Views: 45

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521674

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.

Upvotes: 1

Related Questions