繁体   English   中英

如何删除仅带有特定类名且不包含字符串内部内容的html标签(跨度)?

[英]How to remove html tags (span) wrap only with specific class name and without inner content from a string?

我想从字符串中删除一些不需要的标记,以将干净的字符串存储到数据库中。

我试图将字符串与正则表达式联系起来。 这就是我尝试过的-https: //codepen.io/rushijagani/pen/wZxWRj

var data = '<p><span class="unwanted-span-one" data-hello="unwated-attr">Donec</span> rutrum congue leo eget malesuada. <span>Mauris</span> blandit aliquet elit, eget <span class="unwanted-span-two" data-hello="unwated-attr-two"> malesuada</span>.</p>'

我想删除所有以“ unwanted-span-”开头的类名的span标签,它应该只删除标签包装而不是内容。

因此所需的输出应如下

var data = '<p>Donec rutrum congue leo eget malesuada. <span>Mauris</span> blandit aliquet elit, eget malesuada.</p>'

请注意 - 我们只需要删除类名以“ unwanted-span-”开头的span标签,其他span应该保持原样。

您可以简单地使用

var allData = $('*[class^="unwanted-span-"]').contents().unwrap();
console.log($(".all").html())

如果您不想更改HTML,则可以尝试以下操作:

var match = $('*[class^="unwanted-span-"]').get(0);
var test = $('p').html().replace(match.outerHTML,match.innerHTML);
console.log( test );

当然,如果您有多个比赛,则必须迭代所有比赛:)

您可以使用像这样的操作符开头:

var allData = $('.all').find("span[class^='unwanted-span']").css('color','blue');

我编辑您的Codepen容器https://codepen.io/anon/pen/qwyayP

要删除使用此:

var allData = $('.all').find("span[class^='unwanted-span']").remove(); 

要解开跨度文本,请使用以下命令:

var allData = $('.all').find('span[class^="unwanted-span-"]').contents().unwrap();

console.log($('.all').html());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM