简体   繁体   English

Javascript替换正则表达式除了p,a和img之外的所有html标签

[英]Javascript replace regex all html tags except p,a and img

I'm trying to remove all html tags except p , a and img tags. 我正在尝试删除除paimg标签之外的所有html标签。 Right now I have: 现在我有:

content.replace(/(<([^>]+)>)/ig,""); 

But this removes all HTML tags. 但这会删除所有HTML标记。

This are examples of the content of the api: 这是api内容的示例:

    <table id="content_LETTER.BLOCK9" border="0" width="100%" cellspacing="0" cellpadding="0" bgcolor="#F7EBF5">
<tbody><tr><td class="ArticlePadding" colspan="1" rowspan="1" align="left" valign="top"><div>what is the opposite of...[] rest of text

You may match the tags to keep in a capture group and then, using alternation, all other tags. 您可以匹配标记以保留在捕获组中,然后使用交替匹配所有其他标记。 Then replace with $1 : 然后用$1替换:

(<\/?(?:a|p|img)[^>]*>)|<[^>]+>

Demo: https://regex101.com/r/Sm4Azv/2 演示: https//regex101.com/r/Sm4Azv/2

And the JavaScript demo: 和JavaScript演示:

 var input = 'b<body>b a<a>a h1<h1>h1 p<p>p p</p>p img<img />img'; var output = input.replace(/(<\\/?(?:a|p|img)[^>]*>)|<[^>]+>/ig, '$1'); console.log(output); 

You can use the below regex to remove all HTML tags except a , p and img : 您可以使用以下正则表达式删除除 apimg 之外 a 所有HTML标记

<\/?(?!a)(?!p)(?!img)\w*\b[^>]*>

Replace with an empty string. 替换为空字符串。

 var text = '<tr><p><img src="url" /> some text <img another></img><div><a>blablabla</a></div></p></tr>'; var output = text.replace(/<\\/?(?!a)(?!p)(?!img)\\w*\\b[^>]*>/ig, ''); console.log(output); 

Regex 101 Demo 正则表达式101演示

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

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