2012-07-11 90 views
7

所有特定HTML標籤我有一個包含文本和HTML標記,如字符串的變量:jQuery的:剝去字符串

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 

我想刪除某一類型的所有標籤。比方說,所有pspan標籤。

這是我能拿出最好的:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
var $temp = $(temp); 
$("p", $temp).replaceWith("foo"); 
alert($temp.html()); //returns "Some text" 

我能找到的最接近的反應是這個答案由Nick Craver:strip span tags from string with jquery

+0

那是什麼_certain type_? – undefined 2012-07-11 22:30:52

+0

已編輯的問題:p標籤和span標籤是我想要替換的。但這在未來可能會改變。 – iammatthew2 2012-07-11 22:46:54

回答

12

演示:http://jsfiddle.net/VwTHF/1/

$('span, p').contents().unwrap(); 

.contents()會得到一個元素和文本每個這樣的標籤中,並且.unwrap將移除纏繞每個內容部分中的元素。

根據您目前的做法會是這個樣子:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
var $temp = $(temp); 
$temp.find('span, p').contents().unwrap().end().end(); 

如果你想繼續針對原始對象,你必須使用.end()來清除過濾器。

+0

希望我沒有誤解你的問題。你只是想擺脫標籤,但留下正確的文字? – nbrooks 2012-07-11 22:50:31

+0

是的,我只想刪除某些標籤並保留文本和所有其他標籤。但我無法在上面的例子中得到上述結果:[http://jsfiddle.net/nEFhA/] – iammatthew2 2012-07-11 23:04:12

+0

@ iammatthew2它完美地工作。您忘記了包含jQuery:http:// jsfiddle。net/WPpqE /(你必須在左邊的選項中指定要使用的框架) – nbrooks 2012-07-11 23:05:37

2

您可以試試jquery plugin HTML Clean。在這個例子中,他們提供:

$.htmlClean("<H1 class=\"header\"><P>Nested P Test</H1>", {format:true}); 

=> 
<h1> 
     Nested P Test 
</h1> 

您可以{removeTags:[p]}替換特定的標記,它仍然會呈現的內容只是沒有標籤。

+0

謝謝!我會嘗試一下,但我認爲Jquery只需要幾行代碼就可以處理這個問題。 – iammatthew2 2012-07-11 22:47:25

0

我不得不做一些類似的事情:保留一段文本不能包含除<b><i><u>以外的任何HTML標記。這個問題和其他幾個人指着我對我自己的函數:

function cleanNonFormattingTags(htmlContents) { 
    if (htmlContents && htmlContents.length) { 
     var result = ''; 
     htmlContents.each(function() { 
      var $child = $(this), type = $child.prop('tagName'), isTextNode = this.nodeName == "#text"; 
      if (isTextNode) { 
       result += this.textContent; 
      } 
      else if (type == 'B' || type == 'U' || type == 'I' || type == 'BR') { // Allow only these types of tags 
       var innerContent = cleanNonFormattingTags($child.contents()); 
       var $newTag = $(document.createElement(type)).html(innerContent); 
       result += $newTag[0].outerHTML; 
      } 
      else { 
       result += cleanNonFormattingTags($child.contents()); 
      } 
     }); 
     return result; 
    } 
    return htmlContents.text(); 
} 

希望這有助於!

0

我會跟進@nbrooks,因爲他的回答非常接近你想要的,但並不完全。 @nbrooks通過注意到html()爲您提供包裝在標籤中的數據來解決方案。因此,解決方案是將HTML包裝在標籤中。這應該爲你做的伎倆:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
$("<span>" + temp + "</span>").find('span,p'). 
    contents().unwrap().end().end().html()` 

查看http://jsfiddle.net/18u5Ld9g/1/爲例。

作爲一個更一般的功能:

function stripTags(html, tags) { 
    // Tags must be given in CSS selector format 
    return $("<span>" + html + "</span>").find(tags). 
    contents().unwrap().end().end().html(); 
}