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

标签 javascript regex

我正在尝试删除除 paimg 标签之外的所有 html 标签。现在我有:

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

但这会删除所有 HTML 标签。

这是 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

最佳答案

您可以匹配要保留在捕获组中的标签,然后使用交替匹配所有其他标签。然后替换为$1:

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

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

和 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);

关于Javascript 替换正则表达式除 p、a 和 img 之外的所有 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009089/

相关文章:

javascript - 使用 Ajax 请求执行 PHP 文件

regex - perl:用不同大小的图案替换图案

Python 正则表达式 : Check for match and capture groups

javascript - 使用正则表达式检索浏览器名称

javascript - 为什么 'string' [0]在ie8 + IIS7.5上的行为不同于其他浏览器或本地文件?

javascript - 如何在Summernote编辑器中添加对齐(左对齐、居中对齐、右对齐)工具栏

javascript - Angular.js 在输入 :checkbox 中将 ng-model 与 ng-repeat 绑定(bind)

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL - A simple string syntactically wrong

python - 根据比对修剪序列

java - 需要字符串匹配器正则表达式