Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式替换大括号内的特定单词_Javascript_Regex - Fatal编程技术网

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

Javascript 正则表达式替换大括号内的特定单词,javascript,regex,Javascript,Regex,我想将“wordToReplace”替换为“REPLACED”(在大括号内),使其成为 Hello {#if wordToReplace} World {/if} {#each wordToReplace as item} {item.name} {/item} 如何使用正则表达式实现此目的?您可以尝试搜索正则表达式模式: Hello {#if REPLACED} World {/if} {#each REPLACED as item} {item.name} {/item} 然

我想将“wordToReplace”替换为“REPLACED”(在大括号内),使其成为

Hello

{#if wordToReplace}
 World
{/if}

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

如何使用正则表达式实现此目的?

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

Hello

{#if REPLACED}
 World
{/if}

{#each REPLACED as item}
{item.name}
{/item}
然后替换为:

\{(.*?)\bwordToReplace\b(.*?)\}
var input=“Hello\n\n{{if wordToReplace}\n World\n{/if}\n\n{{if wordToReplace as item}\n{item.name}\n{/item}”;
var output=input.replace(/\{(.*?\b或存储替换\b(.*?\}/g,“{$1REPLACED$2}”);
控制台日志(输入);
控制台日志(输出)
{$1 REPLACED $2}