2017-05-25 41 views
-1

我有這個字符串。我想刪除有id的span而不刪除數據。正則表達式刪除有ID沒有數據的跨度

輸入: VAR的TestString = "<span class="test01">Electrical drafting Scheduling tools <span id="spcc15in0os0">draftin</span><span> </span> Scheduling tools Mechanical</span>"

預期輸出:

"<span class="test01">Electrical drafting Scheduling tools draftin<span> </span> Scheduling tools Mechanical</span>" 

我是新來的正則表達式。嘗試了幾件事情。

Try1:testString.replace(/<\/?span\sid=[^>]*>/g, "") 結果:但它不刪除跨度的結束標記

Try2:testString.replace(/(<span id=".*"(?: \w+="[^"]+")*>([^<]*)<\/span>)/gi, "") 結果:它是除去具有與數據ID跨度。

+3

不使用正則表達式來解析HTML內容 –

+0

作爲@ArunPJohny說,[**請勿使用正則表達式來解析HTML **](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)你可以,但是,使用jQuery,只是把你的HTML '$(myStringHere)'中的字符串' – George

+0

你想在哪個環境中解析這個字符串?服務器/客戶端?如果你有可用的javascript,你可以使用[innerHTML](https://www.w3schools.com/jsref/prop_html_innerhtml.asp)來簡化它, –

回答

0

如果你不需要,你不應該通過正則表達式解析HTML。您標記您的文章與jquery,所以這可能是工作爲你:

var testString = "<span class='test01'>Electrical drafting Scheduling tools <span id='spcc15in0os0'>draftin</span><span> </span> Scheduling tools Mechanical</span>"; 
 

 
var $element = $(testString); 
 
$element.find("span").each(function(index) { 
 
    var innerText= $(this).text(); 
 
    $(this).replaceWith(innerText); 
 
}); 
 

 
var newString = $element.html(); 
 

 
console.log(newString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>