Peter Pik Peter Pik - 2 months ago 20
Node.js Question

Remove empty p tags and convert other p tags to \n

I'm using cheerio and i have some html like this:

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


i'm wondering how i can format this html to something like this using javascript and cheerio.

test\ntest\ntest


so that if its an empty p tag it should be remove otherwise change it to an \n

Answer
  1. Select the paragraphs
  2. Filter out the empty ones
  3. Map the text
  4. Turn it into an array
  5. Join the array to map the string

.

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
Comments