In this blog post, we will explore how to fix and improve a function written in Google Apps Script that removes blank lines from a Google Docs document. This can be particularly useful for cleaning up documents with unnecessary blank lines.
Original Function
Here is the original removeBlankLines
function:
function removeBlankLines(docId) {
try {
var doc = DocumentApp.openById(docId);
var body = doc.getBody();
var paragraphs = body.getParagraphs();
for (var i = paragraphs.length - 1; i > 0; i--) { // Change condition to `i > 0`
var text = paragraphs[i].getText().trim();
if (text === '') {
body.removeChild(paragraphs[i]);
}
}
// Check the first paragraph separately
var firstParagraphText = paragraphs[0].getText().trim();
if (firstParagraphText === '' && paragraphs.length > 1) {
body.removeChild(paragraphs[0]);
}
} catch (e) {
Logger.log('Error: ' + e.message);
}
}
Issues with the Original Function
- Undeclared Variable
DOCID
: The variableDOCID
is not defined within the function. This needs to be provided as a parameter or defined within the function. - Trim Method: The
trim()
method is correctly used to remove whitespace from the beginning and end of the string. - Looping in Reverse: The function correctly loops through the paragraphs array in reverse to avoid issues with removing elements while iterating.
Improved Function
To address the issues, we’ll make the following improvements:
- Add
DOCID
as a Parameter: This allows the function to be more flexible by accepting the document ID as an argument. - Error Handling: Add basic error handling to manage cases where the document ID is incorrect or the document cannot be accessed.
Here is the improved version of the removeBlankLines
function:
function removeBlankLines(docId) {
try {
var doc = DocumentApp.openById(docId);
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]);
}
}
} catch (e) {
Logger.log('Error: ' + e.message);
}
}
Explanation of the Improved Function
- Parameter
docId
: The function now takesdocId
as a parameter, making it reusable for different documents. - Error Handling: The
try...catch
block ensures that any errors encountered during the execution are logged, helping with debugging.
How to Use the Function
To use this function, you need to pass the Google Docs document ID as an argument. Here’s an example of how to call this function:
function cleanDocument() {
var docId = 'your-google-doc-id-here';
removeBlankLines(docId);
}
Conclusion
In this post, we fixed and improved a Google Apps Script function to remove blank lines from a Google Docs document. By making the DOCID
a parameter and adding error handling, we enhanced the function’s usability and robustness. This approach can help keep your documents clean and organized.
