How to Remove Blank Lines from a Google Docs Document Using Google Apps Script

Removing extra blank lines from a Google Doc can be a tedious and time-consuming task, especially when dealing with large documents. While Google Docs has a Find and Replace feature, it doesn’t always catch all types of blank lines.

With Google Apps Script, you can automate the process of removing these blank lines, saving you time and effort. In this post, we’ll walk through an effective script that removes blank lines from a document while avoiding the “Can’t remove the last paragraph” error.

This solution guarantees the last paragraph is never deleted, and it efficiently removes lines that are completely blank or only contain whitespace.


Why Remove Blank Lines?

Blank lines often appear due to:

  • Copy-pasting content from other sources.
  • Unintentional line breaks while editing.
  • Formatting issues caused by imported documents.

Removing them makes your document cleaner and more professional. It also saves space and enhances readability, especially in reports, e-books, and scripts.


The Full Script

Here’s the complete Google Apps Script for removing blank lines from a Google Doc. This script works by:

  1. Accessing each paragraph in the document.
  2. Checking for blank lines (lines that are completely empty or contain only whitespace).
  3. Skipping the last paragraph to avoid the “Can’t remove the last paragraph in a document section” error.

Complete Script

function remove2EmptyLines() {
const DOCID = 'YOUR_DOCUMENT_ID_HERE'; // Replace with your document ID
const doc = DocumentApp.openById(DOCID);
const body = doc.getBody();
const paragraphs = body.getParagraphs();

// Iterate through paragraphs from bottom to top
for (let i = paragraphs.length - 1; i >= 0; i--) {
const paragraph = paragraphs[i];
const text = paragraph.getText().trim();

// Skip the last paragraph in the document section
if (i === paragraphs.length - 1) {
Logger.log("Skipping the last paragraph to avoid exceptions.");
continue;
}

// Check if the paragraph is empty or contains only whitespace
if (text === '') {
body.removeChild(paragraph);
}
}

Logger.log("Empty and blank lines have been removed, except the last paragraph.");
}

How It Works

Here’s a breakdown of the key sections of the script.

1. Open the Google Doc

const DOCID = 'YOUR_DOCUMENT_ID_HERE'; 
const doc = DocumentApp.openById(DOCID);
const body = doc.getBody();
  • Replace YOUR_DOCUMENT_ID_HERE with the unique document ID of the Google Doc where you want to remove blank lines.
  • The DocumentApp.openById() method opens the document, and getBody() allows us to access and edit its main content.

2. Get All Paragraphs

const paragraphs = body.getParagraphs();
  • This method retrieves all the paragraphs in the document as an array.
  • Each paragraph is an object that we can modify or remove.

3. Loop Through Paragraphs in Reverse

for (let i = paragraphs.length - 1; i >= 0; i--) {
  • We iterate backward through the paragraphs to avoid index shifting issues.
  • When you delete a paragraph while looping forward, the paragraph indices change.
  • By working from the end of the document toward the beginning, this issue is avoided.

4. Skip the Last Paragraph

if (i === paragraphs.length - 1) {
Logger.log("Skipping the last paragraph to avoid exceptions.");
continue;
}
  • Google Docs requires that at least one paragraph remains in every document.
  • If you attempt to remove the last paragraph, you’ll get the error “Can’t remove the last paragraph in a document section.”
  • To avoid this, we skip the last paragraph by checking if i is the last paragraph in the document.

5. Check If the Paragraph is Blank

const text = paragraph.getText().trim();
if (text === '') {
body.removeChild(paragraph);
}
  • The paragraph.getText() method returns the paragraph’s content as a string.
  • trim() removes any leading or trailing whitespace, so paragraphs that only contain spaces or tabs will be counted as blank.
  • If the paragraph is blank (text === ''), it is removed from the document using body.removeChild(paragraph).

Example

Before Running the Script

This is paragraph 1.

(Blank line with spaces)

(Another blank line)

This is paragraph 2.

(Blank line with tabs) (Another blank line)
This is paragraph 3.

After Running the Script

csharpCopy codeThis is paragraph 1.

This is paragraph 2.

This is paragraph 3.

The blank lines (even those with spaces or tabs) are removed, but the last paragraph is left intact.


Key Features

  • Skips the Last Paragraph: Avoids the “Can’t remove the last paragraph in a document section” error.
  • Removes Blank Lines: Removes blank lines (lines with only spaces, tabs, or no text).
  • Works with Large Documents: Processes the entire document, regardless of its size.
  • Backward Loop: Loops backward to avoid index issues when paragraphs are removed.

Customizations

This script can be tailored to handle different scenarios.

1. Remove Blank Paragraphs with Specific Conditions

Instead of removing all blank paragraphs, you may want to only remove consecutive blank paragraphs. Here’s how to do it:

let previousWasBlank = false;
for (let i = paragraphs.length - 1; i >= 0; i--) {
const paragraph = paragraphs[i];
const text = paragraph.getText().trim();

if (i === paragraphs.length - 1) continue;

if (text === '' && previousWasBlank) {
body.removeChild(paragraph);
}

previousWasBlank = (text === '');
}

This script removes consecutive blank paragraphs but leaves a single blank line between text blocks.


2. Process Only a Specific Section of the Document

If you want to work only on a specific section (like after a heading), use getChild() and process only that portion:

const headerIndex = 2; // Start at the 3rd section
const child = body.getChild(headerIndex);
const paragraphs = child.getParagraphs();

for (let i = paragraphs.length - 1; i >= 0; i--) {
const paragraph = paragraphs[i];
const text = paragraph.getText().trim();

if (text === '') {
child.removeChild(paragraph);
}
}

This script only processes the paragraphs that appear after the 3rd child element (which could be a heading).


3. Use Triggers to Automate Cleaning

You can automate the blank-line cleanup to run every hour or every day:

  1. Open Extensions > Triggers.
  2. Add a trigger for the remove2EmptyLines function to run hourly or daily. This ensures that any Google Docs you use frequently remain clean and free of blank lines.

Common Issues & Fixes

IssueCauseSolution
“Can’t remove last paragraph”Last paragraph cannot be removedThe script automatically skips the last paragraph.
Paragraphs not removedParagraphs have invisible charactersThe trim() method handles this, so no issue.
Rate limitsToo many operations in large docsProcess in chunks (add Utilities.sleep(500)).
Script times outLarge document processingProcess in chunks, or use a trigger to resume processing.

Final Thoughts

This Google Apps Script is a simple and effective way to remove blank lines from a Google Doc. It works on paragraphs containing only spaces, tabs, or empty lines, and it avoids the last-paragraph error. The script works even on large documents and can be customized to handle specific sections or apply different removal conditions.

With this script, you’ll save hours of manual editing. If you’d like any customizations (like handling specific sections or consecutive blank lines), just let me know! 🚀

Key Features Recap

  • Removes blank lines while keeping document structure intact.
  • Works on large documents and avoids Google Apps Script limits.
  • Never deletes the last paragraph of the document.