删除空的p标签并将其他p标签转换为\ n

时间:2016-09-16 12:05:47

标签: javascript node.js cheerio

我正在使用cheerio,我有一些像这样的HTML:

<p></p>
<p>test</p>
<p>&nbsp;</p>
<p>test</p>
<p>&nbsp;</p>
<p>test</p>

我想知道如何使用javascript和cheerio将这个html格式化为这样的东西。

test\ntest\ntest

因此,如果它是一个空的p标签,则应将其删除,否则将其更改为\ n

3 个答案:

答案 0 :(得分:3)

jQuery(document).ready(function(e) {
jQuery('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s|&nbsp;/g, '').length == 0)
   $this.remove();
});
});

答案 1 :(得分:2)

  1. 选择段落
  2. 过滤掉空的
  3. 映射文字
  4. 将其变为数组
  5. 加入数组以映射字符串
  6. var txt = $('p')   //1
                .filter(function(i, el) {  //2
                    return $(this).text().replace(/\s+|&nbsp;/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';
  }
});