Removing blank lines from an all text Google DOC 2

32 views Asked by At

I have an all text Google Doc but it have a lot of places where there are more than 1 blank line/paragraph in a row. I have tried the code below but it stops at "line.removeFromParent()". I would like to remove any extra blank lines leaving only one in each place of a group of them. The code that I tried is:

function removeEmptyLines() {
  const s = SlidesApp.getActivePresentation();
  let docname = s.getName();
  let doc = DocumentApp.create("Notes - " + docname);
 
  Logger.log("Before:\n", doc.getBody().getText());  
  
  var paragraphs = doc.getBody().getParagraphs();
  // Iterating from the last paragraph to the first
  for (var i=paragraphs.length-1; i>=0; i--){
    var line = paragraphs[i];
    if ( ! line.getText().trim() ) {
      // Paragraph (line) is empty, remove it
      line.removeFromParent()
      Logger.log("Removed: ", i);
    }
  }
  Logger.log("After:\n", doc.getBody().getText());
}

I also tried the following it ran but it did not work:

const s = SlidesApp.getActivePresentation();
 let docname = s.getName();
 let doc = DocumentApp.create("Notes - " + docname);
 let docId = doc.getId();
 var doc2 = DocumentApp.openById(docId);
 var body3 = doc2.getBody() var paras = body3.getParagraphs();
 var i = 0;
 for (var i = 0; i < paras.length;
 i++) { if (paras[i].getText() === ""){ paras[i].removeFromParent()
 }
 } 
0

There are 0 answers