【发布时间】:2020-08-21 09:58:02
【问题描述】:
我需要去除 HTML 标签的正则表达式,除了包含类“classmark”的“a”标签
假设我有这个 HTML 字符串:
<b>this</b>
<a href="#">not match</a>
<a href="#" target="_blank">not match</a>
<a href="#" class="classmark" target="_blank">match</a>
<a href="#" class="classmark">match2</a>
<a class="classmark" target="_blank">match3</a>
<a class="classmark">match4</a>
<b>this</b>
<p>fggfgf</p>
我想要这样的结果:
this
not match
not match
<a href="#" class="classmark" target="_blank">match</a>
<a href="#" class="classmark">match2</a>
<a class="classmark" target="_blank">match3</a>
<a class="classmark">match4</a>
this
fggfgf
我使用这个函数来去除 HTML 标签
function strip_tags( _html /*you can put each single tag per argument*/ )
{
var _tags = [], _tag = "" ;
for( var _a = 1 ; _a < arguments.length ; _a++ )
{
_tag = arguments[_a].replace( /<|>/g, '' ).trim() ;
if ( arguments[_a].length > 0 ) _tags.push( _tag, "/"+_tag );
}
if ( !( typeof _html == "string" ) && !( _html instanceof String ) ) return "" ;
else if ( _tags.length == 0 )
{
return _html.replace( /<(\s*\/?)[^>]+>/g, "" );
}
else
{
var _re = new RegExp( "<(?!("+_tags.join("|")+")\s*\/?)[^>]+>", "g" );
return _html.replace( _re, '');
}
}
它会去除 HTML 标签,只保留我想要相同功能的特定标签,并添加我需要的类属性,如下所示:
strip_tags( HTMLstring , "a" ,"classmark")
【问题讨论】:
标签: javascript html tags strip