I have a javascript function performing filtering on strings. I currently have the filter stripping out all html tags.
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.
I'm not too familiar with regEx. How could I specify /<[^>]+>/gm
to be only opening or closing?
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.
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.