【问题标题】:strip html tags except a tag that contain class除去包含类的标签之外的 html 标签
【发布时间】: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


    【解决方案1】:

    如果我理解正确,您可以使用正则表达式来测试 html 是否包含带有类属性 y 的标签 x,然后您可以使用 .replace(regex, ...) 调用剥离标签。这可能是这样的:

    [removed]
    

    编辑:

    好的,误解并认为它是单个 html 标签的数组。所以这个版本首先将它们分成匹配的 html 标签(注意这个版本不会做嵌套标签),然后它映射到所有部分并替换每个部分。然后加入他们:

    function strip_tags(_html, _tag, _class) {
      return _html
        // Match each tag and return them as an array of matches
        .match(/<(.+).*?>.*?<\/\1>(.*?)([^<]*)/g) 
        // Map over each tag and check if it is a specific tag with a specific class
        .map(tag => {
          const regex = RegExp(`<${_tag} (.*?)class="${_class}"(.*?)>`);
          // If it is, replace the tag part within nothing, and leave the content
          if (!regex.test(tag)) {
            return tag.replace(/(<([^>]+)>)/gi, '');
          // If not then just return the tag as is 
          } else {
            return tag;
          }
        })
        // Now join all the mapped tags back together
        .join('');
    }
    

    编辑:

    如果您想要一个合适的 HTML 解析器并检查每个元素,那么您可以查看 DOMParserthis link to start with

    let parser = new DOMParser()
    let doc = parser.parseFromString(str, "text/html")
    doc
      .querySelectorAll('*')
      .forEach(node => {
        console.log(node);
      });
    

    【讨论】:

    • 如果这样的字符串:"test@test" 会保留仅:“测试@test”?
    • 如果我像你一样测试功能我得到结果:“test@test”?
    • 你的函数不会工作,因为它不是一个一个地测试整个 HTML 字符串
    • 对。现在编辑答案。
    • 检查这个:'test@testtest' 我需要这样的结果:'test@test测试'
    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 2023-03-10
    • 1970-01-01
    • 2011-09-08
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多