[英]Regex find all closing html tags, all opening separately
I have a javascript function performing filtering on strings. 我有一个JavaScript函数对字符串执行过滤。 I currently have the filter stripping out all html tags. 我目前有过滤器剥离所有html标记。
return String(text).replace(/<[^>]+>/gm, '');
I've realized that I actually need to perform two operations: First, to replace all closing tags with <br>
and then a second operation to remove all opening tags. 我已经意识到我实际上需要执行两个操作:首先,用<br>
替换所有结束标记,然后执行第二次操作,删除所有开始标记。
I'm not too familiar with regEx. 我对regEx不太熟悉。 How could I specify /<[^>]+>/gm
to be only opening or closing? 如何指定/<[^>]+>/gm
仅是打开还是关闭?
You need to use double replace function. 您需要使用双重替换功能。
> var str = "<h1>foo bar</h1>"
undefined
> str.replace(/<\w[^>]*>/, "").replace(/<\/[^>]+>/, "<br>")
'foo bar<br>'
OR 要么
Use single replace function which uses a capturing group based regex. 使用单个替换功能,该功能使用基于捕获组的正则表达式。
> var str = "<h1>foo bar</h1>"
> str.replace(/<(\w+\b)[^>]*>([^<>]*)<\/\1>/, '$2<br>')
'foo bar<br>'
We must back-reference ( \\1
) to the first capturing group instead of second because the 1st itself contain the tag-name. 我们必须向后引用( \\1
)第一个捕获组,而不是第二个,因为第一个捕获组本身包含标记名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.