[英]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.