Google Apps Script that removes blank lines from a Google Doc

Google Apps Script that removes blank lines from a Google Doc, you can use the following script. This script iterates through all the paragraphs in the document and checks if any of them are empty (i.e., contain only whitespace characters or nothing at all). If an empty paragraph is found, it is removed from the document.

function removeBlankLines() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();
  
  // Iterate backwards through the paragraphs to avoid index shifting issues
  for (var i = paragraphs.length - 1; i >= 0; i--) {
    var paragraphText = paragraphs[i].getText().trim();
    // Check if the paragraph is empty
    if (paragraphText === '') {
      // Remove the empty paragraph
      body.removeChild(paragraphs[i]);
    }
  }
}

How to Use This Script:

  1. Open the Google Doc from which you want to remove blank lines.
  2. Go to Extensions > Apps Script.
  3. Delete any code in the script editor and paste the above script.
  4. Save the script with a name, for example, RemoveBlankLines.
  5. Run the script by clicking the play (▶️) button or selecting the function removeBlankLines from the dropdown next to the play button and then clicking it.

This script efficiently removes all blank lines from your document, improving document neatness and reducing unnecessary space. The script works by trimming whitespace from each paragraph’s text to ensure that lines with spaces or tabs but no visible content are also considered blank and thus removed.

Be cautious when running scripts that modify your document, especially on large documents, as the changes made are not easily reversible without using the document’s version history.