简体   繁体   English

如何使用javascript正则表达式删除部分字符串而不重复分隔字符串

[英]How to remove part of string with javascript regex without repeating delimiting strings

I would like to remove an unknown substring when it occurs between two known substrings ( <foo> and </foo> ). 我希望在两个已知子字符串( <foo></foo> )之间删除未知子字符串。 For example, I'd like to convert: 例如,我想转换:

hello <foo>remove me</foo>

to: 至:

hello <foo></foo>

I can do it with: 我可以这样做:

s = ...
s.replace(/<foo>.*?<\/foo>/, '<foo></foo>')

but I'd like to know if there's a way to do it without repeating the known substrings ( <foo> and </foo> ) in the regex and the replacement text. 但我想知道是否有办法在不重复正则表达式和替换文本中的已知子串( <foo></foo> )的情况下执行此操作。

You can capture tag in a captured group and use it later as back reference: 您可以捕获captured group标记,并在以后将其用作后向引用:

var repl = s.replace(/<(foo)>.*?<\/\1>/, '<$1></$1>');
//=> hello <foo></foo>

Note \\1 and $1 are back references to the captured group #1. 注意\\1$1是对捕获的组#1的反向引用。

在此输入图像描述

Try below regex using grouping. 使用分组尝试以下正则表达式。

(?:<foo>)(.*?<\/foo>)

regex101 online demo regex101在线演示

Pictorial representation: Debuggex Demo 图示Debuggex演示

在此输入图像描述

Sample code: 示例代码:

var re = /(?:<foo>)(.*?<\/foo>)/;
var str = 'hello <foo>remove me</foo>';
var subst = '<foo></foo>';

var result = str.replace(re, subst);

Output: 输出:

hello <foo></foo>

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

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