删除空的 p 标签并将其他 p 标签转换为 \n
Remove empty p tags and convert other p tags to \n
我正在使用 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
- Select 段落
- 过滤掉空的
- 映射文本
- 转成数组
- 加入数组映射字符串
.
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
如果您的 html 在 html
中,这样的事情应该有效:
var $ = cheerio.load(html);
var result = '';
$('body').each(function() {
if ($(this).find('p').contents().length) {
result += $(this).text() + '\n';
}
});
jQuery(document).ready(function(e) {
jQuery('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
});
我正在使用 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
- Select 段落
- 过滤掉空的
- 映射文本
- 转成数组
- 加入数组映射字符串
.
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
如果您的 html 在 html
中,这样的事情应该有效:
var $ = cheerio.load(html);
var result = '';
$('body').each(function() {
if ($(this).find('p').contents().length) {
result += $(this).text() + '\n';
}
});
jQuery(document).ready(function(e) {
jQuery('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
});