Jquery:从字符串中删除所有特定的HTML标记

我有一个包含一串文本和html标签的变量,例如:

var temp = "
Some text

More texthere

Even more

";

我想删除某种类型的所有标签。 比如说所有的pspan标签。

这是我能想到的最好的:

 var temp = "
Some text

More texthere

Even more

"; var $temp = $(temp); $("p", $temp).replaceWith("foo"); alert($temp.html()); //returns "Some text"

我能找到的最接近的答案是Nick Craver的答案: 带有jquery的字符串的span span标签 。

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

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

.contents()将获取每个此类标记内的元素和文本,而.unwrap将删除包装每个内容部分的元素。

根据您当前的方法,它看起来像这样:

 var temp = "
Some text

More texthere

Even more

"; var $temp = $(temp); $temp.find('span, p').contents().unwrap().end().end();

如果要继续定位原始对象,则必须使用.end()清除filter。

您可以尝试使用jquery插件HTML Clean 。 在他们提供的示例中:

 $.htmlClean("

Nested P Test

", {format:true}); =>

Nested P Test

您可以使用{removeTags:[p]}替换特定标记,它仍然会使内容不是标记。

我必须做类似的事情:保持一个文本块不包含除之外的任何HTML标记。 这个问题和其他几个问题指出了我自己的function:

 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(); } 

希望这可以帮助!

我会跟进@nbrooks,因为他的回答非常接近你想要的,但并不完全。 @nbrooks注意到解决方案,注意到html()为你提供了包含在标签中的数据。 因此,解决方案是将HTML包装在标记中。 这应该是你的诀窍:

 var temp = "
Some text

More texthere

Even more

"; $("" + temp + "").find('span,p'). contents().unwrap().end().end().html()`

有关示例,请参见http://jsfiddle.net/18u5Ld9g/1/ 。

作为更一般的function:

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