我正在尝试删除除 p
、a
和 img
标签之外的所有 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/