我正在使用cheerio,我有一些像这样的HTML:
<p></p>
<p>test</p>
<p> </p>
<p>test</p>
<p> </p>
<p>test</p>
我想知道如何使用javascript和cheerio将这个html格式化为这样的东西。
test\ntest\ntest
因此,如果它是一个空的p标签,则应将其删除,否则将其更改为\ n
答案 0 :(得分:3)
jQuery(document).ready(function(e) {
jQuery('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
});
答案 1 :(得分:2)
var txt = $('p') //1
.filter(function(i, el) { //2
return $(this).text().replace(/\s+| /g,"").length;
}).map( function () { //3
return $(this).text();
})
.get() //4
.join("\n"); //5
答案 2 :(得分:0)
如果你的html在html
中,那么这样的东西应该有效:
var $ = cheerio.load(html);
var result = '';
$('body').each(function() {
if ($(this).find('p').contents().length) {
result += $(this).text() + '\n';
}
});