Google Apps Script that removes all blank lines from a Google Docs document

To create a Google Apps Script that removes all blank lines from a Google Docs document, you can iterate through all the elements in the document body and check if any paragraph elements consist only of whitespace or are empty. If so, you can remove those elements. This script operates on the active document, so make sure you have the document open and you’re authorized to edit it.

Here’s how you can write this script:

function removeBlankLines() {
  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();
  var totalElements = body.getNumChildren();
  // Iterate through all elements in reverse order
  for (var i = totalElements - 1; i >= 0; i--) {
    var element = body.getChild(i);
    // Check if the element is a paragraph
    if (element.getType() === DocumentApp.ElementType.PARAGRAPH) {
      var text = element.asParagraph().getText().trim();
      // If the paragraph is empty or contains only whitespace, and it's not the last paragraph in the document
      if (text === '' && !(i === 0 && totalElements === 1)) {
  // After removing blank lines, ensure there's at least one paragraph in the document
  if (body.getNumChildren() === 0) {

How to Use This Script:

  1. Open your Google Docs document: Navigate to the Google Docs document you want to clean up.
  2. Open the Script Editor: Go to Extensions > Apps Script from the Google Docs menu.
  3. Create the Script: Copy and paste the provided script into the script editor.
  4. Save and Name Your Project: Click the floppy disk icon or File > Save, and give your project a name.
  5. Run the Script: Click the play (▶️) button to run the removeBlankLines function. You might need to authorize the script to run under your Google account the first time.
  6. Return to Your Document: After the script has run, return to your Google Docs document and refresh the page to see the changes.

Please note, for the script to run, you need to grant it permissions to edit and manage your documents. Follow the prompts for authorization carefully, ensuring you’re comfortable with the permissions being granted. This script is a straightforward way to clean up your document by removing any unnecessary blank spaces, making it more professional and easier to navigate.