How to find and remove blank paragraphs in a Google Document with Google Apps Script?

后端 未结 2 809
梦如初夏
梦如初夏 2020-12-21 03:55

I am working with Google documents that contain hundreds of empty paragraphs. I want to remove these blank lines automatically.

In LibreOffice Writer you can use th

相关标签:
2条回答
  • 2020-12-21 04:34

    I think there has to be a last empty paragraph but this seems to work.

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
    
      var paras = body.getParagraphs();
      var i = 0;
    
      for (var i = 0; i < paras.length; i++) {
           if (paras[i].getText() === ""){
              paras[i].removeFromParent()
           }
    }
    }
    
    0 讨论(0)
  • Adding to Tom's answer and apmouse's comment, here's a revised solution that: 1) prevents removing paragraphs consisting of images or horizontal rules; 2) also removes paragraphs that only contain whitespace.

    function removeEmptyParagraphs() {
      var pars = DocumentApp.getActiveDocument().getBody().getParagraphs();
      // for each paragraph in the active document...
      pars.forEach(function(e) {
        // does the paragraph contain an image or a horizontal rule?
        // (you may want to add other element types to this check)
        no_img = e.findElement(DocumentApp.ElementType.INLINE_IMAGE)    === null;
        no_rul = e.findElement(DocumentApp.ElementType.HORIZONTAL_RULE) === null;
        // proceed if it only has text
        if (no_img && no_rul) {
          // clean up paragraphs that only contain whitespace
          e.replaceText("^\\s+$", "")
          // remove blank paragraphs
          if(e.getText() === "") {
            e.removeFromParent();
          }
        }    
      })
    }
    
    0 讨论(0)
提交回复
热议问题