2012-07-11 60 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(); 
}