剥离每个子元素的html

让我说我有这样的肮脏的HTML …

let dirty = ` <pre> pre tag with <b>html</b> </pre> <pre> another pre tag with <b>html</b> </pre> ` 

我需要从每个孩子的标签剥离HTML …

即时通讯做这个…

 let $ = cheerio.load(dirty) $('pre').each(function() { let text = $(this).text() console.warn(text) // html are stripped return `<pre>${text}</pre>` }); console.log($.html()) // html are not stripped 

我错过了什么?

 $('pre').each(function() { let text = $(this).text() // You need to inject cleaned string into the DOM $(this).html(text) }); console.log($('div').html()) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <pre> pre tag with <b>html</b> </pre> <pre> another pre tag with <b>html</b> </pre> </div> 

首先,请注意,虽然技术上可以用反引号分隔多行string,但在IE中完全不支持,因此无法可靠地使用。 您需要使用引号( ' )或双引号( " )。

你的逻辑问题是你在每个循环中定义了可变的text ,但是什么都不做,因为从each()返回是多余的。

为了解决这个问题,你可以简单地使用text()方法去掉给定元素中的任何子HTML。 尝试这个:

 let dirty = '<pre>pre tag with <b>html</b></pre><pre>another pre tag with <b>html</b></pre>'; $('body').append(dirty); $('pre').text(function(i, t) { return t; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

你需要实际分配新的HTML,现在你不要把HTML设置为别的。 以下将工作

 const cheerio = require("cheerio"); let dirty = ` <pre> pre tag with <b>html</b> </pre> <pre> another pre tag with <b>html</b> </pre> `; let $ = cheerio.load(dirty); $("pre").each(function() { $(this).html($(this).text()); }); console.log($.html());