Peter Pik Peter Pik - 1 month ago 7x
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:


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


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

  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