【问题标题】:JS/Jquery/RegEx - Remove all tags except the ones with classname XYZJS/Jquery/RegEx - 删除除类名 XYZ 之外的所有标签
【发布时间】:2010-09-11 09:58:35
【问题描述】:

这让我发疯 ;-) 我有一个带有各种跨度标签的字符串...我想删除所有跨度标签,除了类名 XYZ 的标签...问题是我还没有找到一个解决方案来离开结束标签...

我的出发点是这个正则表达式:

 text = text.replace(/<\/?[^>]+(>|$)/g, "");

但是我想说的一切“如果 MATCH classnameXYZ 到现在都失败了,不要这样做......

有什么想法吗? 提前致谢!

【问题讨论】:

    标签: regex class tags


    【解决方案1】:

    好的,这可以满足我的需要 ;-)

                    $('#text > span').each(function(intIndex){
                        var word;
                        if ($(this).hasClass('checked')) {
                            word = "<span>"+$(this).html()+"</span>";
                        } else {
                            word = $(this).html();
                            word = word.replace(/<\/?[^>]+(>|$)/g, "");
                        }
                        console.log(word);
                    });
    

    【讨论】:

      【解决方案2】:

      这可以在没有正则表达式的情况下完成,更多的是你的answer需要缓存整个html,这会很慢,试试下面的代码,它可能会有所帮助:)

      $(function()
          $('#text > span').each(function() {
             if(!$(this).hasClass('XYZ')) { 
                 $(this).remove();
             }
          });
      });
      

      【讨论】:

      • 在您的问题Remove all tags except the ones with classname XYZ 中删除所有标签是什么意思?它不是指删除整个元素吗?
      猜你喜欢
      • 2013-05-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多