Remove blank lines in your Google Doc with Apps Script

To create an Apps Script that removes blank lines from a Google Docs document, you can follow these steps. This script will go through the document, identify any paragraphs that consist only of whitespace or are completely empty, and remove them.

  1. Open your Google Docs document.
  2. Click on “Extensions” > “Apps Script” to open the script editor for your document.
  3. Delete any code in the script editor and replace it with the following script.
  4. Name your project, for example, “RemoveBlankLines”.
  5. Save the script by clicking the floppy disk icon or pressing Ctrl+S (Cmd+S on Mac).
  6. Close the script editor, and then run the script from the Apps Script dashboard or create a custom menu in your Google Docs for easier access.

Here’s the Apps Script:

function removeBlankLines() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();
  
  for (var i = paragraphs.length - 1; i >= 0; i--) {
    var text = paragraphs[i].getText().trim();
    if (text === '') {
      body.removeChild(paragraphs[i]);
    }
  }
}

This script retrieves all the paragraphs in the document and iterates through them in reverse order. It checks if a paragraph’s text, after being trimmed of whitespace, is empty (''). If so, the paragraph is removed from the document. Iterating in reverse order is important because removing elements from the array as you iterate through it can cause you to skip elements otherwise.

To Run the Script:

  • After saving your script, click on the play (▶️) button in the toolbar of the script editor to execute it. You’ll likely be prompted to authorize the script to run under your Google account, which is necessary for the script to access and modify your document.

Important Notes:

  • Before running this script on an important document, consider testing it on a copy to ensure it works as expected.
  • Google Apps Script operates within certain quotas and limitations, which are typically generous enough for personal use but can be exceeded with extensive operations across many documents or very large documents.

This script provides a straightforward way to clean up your Google Docs documents by removing unwanted blank lines.