Introduction: Have you ever encountered a Google Docs document cluttered with empty or blank lines? These unnecessary spaces can make your document look unprofessional and harder to read. Thankfully, with the power of Google Apps Script, you can automate the process of identifying and removing all empty or blank lines in your document. In this blog post, we’ll show you how to create and run a script that does just that!
What is Google Apps Script? Google Apps Script is a cloud-based scripting platform that allows you to automate tasks and extend the functionality of Google Workspace apps like Docs, Sheets, and Drive. It’s simple to use and requires only basic knowledge of JavaScript.
Why Remove Blank Lines? Blank lines often creep into documents during editing, especially in collaborative environments. Removing them can:
- Improve the document’s readability.
- Save time when formatting.
- Ensure consistent styling for professional results.
The Script: Here’s the Google Apps Script that removes all empty and blank lines from a Google Docs document:
function removeEmptyLines() {
const doc = DocumentApp.getActiveDocument();
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:
- Access the Document: The script retrieves the current active Google Doc using
DocumentApp.getActiveDocument()
. - Iterate Through Paragraphs: It loops through all the paragraphs in the document.
- Identify Blank Lines: By checking if a paragraph’s trimmed text (
trim()
removes extra spaces) is empty, the script identifies blank lines. - Remove Blank Lines: The
removeChild()
method removes the empty paragraph from the document.
Step-by-Step Guide to Implement:
- Open your Google Docs document.
- Go to Extensions > Apps Script.
- Copy and paste the script above into the Apps Script editor.
- Save the script and give it an appropriate name (e.g., “Remove Blank Lines”).
- Close the Apps Script editor and return to your document.
- Run the script:
- Open the Extensions > Apps Script menu.
- Select Run > removeEmptyLines.
- Review your cleaned-up document!
Before and After Example:
Before:
Line 1
Line 2
Line 3
After:
Line 1
Line 2
Line 3
Conclusion: With just a few lines of code, you can easily clean up your Google Docs and remove all unnecessary blank lines. This simple script is a great way to enhance your workflow and ensure your documents are always polished and professional.