Apps Script that adds a blank line above every occurrence of the word

Apps Script Code

function addBlankLineAndBoldExplanation() {
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 all paragraphs in the document
for (let i = 0; i < paragraphs.length; i++) {
const paragraph = paragraphs[i];
const text = paragraph.getText().trim();

// Check if the paragraph contains "Explanation:"
if (text.startsWith("Explanation:")) {
// Bold the word "Explanation:"
const startIndex = text.indexOf("Explanation:");
const endIndex = startIndex + "Explanation:".length;
paragraph.editAsText().setBold(startIndex, endIndex - 1, true);

// Insert a blank line above this paragraph
body.insertParagraph(i, "");
i++; // Skip the inserted blank line to avoid reprocessing
}
}

Logger.log("Added blank lines and bolded 'Explanation:' in the document.");
}

How It Works

  1. Target Paragraphs:
    • The script iterates through all paragraphs in the document using getParagraphs().
  2. Check for “Explanation:”:
    • It checks if the paragraph starts with “Explanation:” using text.startsWith("Explanation:").
  3. Bold the Text:
    • The script identifies the start and end indices of the word “Explanation:” and uses editAsText().setBold() to bold the text.
  4. Insert Blank Line:
    • A blank line is inserted above the paragraph using body.insertParagraph(i, "").
  5. Adjust Index:
    • After inserting a blank line, the loop skips over it to avoid reprocessing.

Example

Before:

This is a normal paragraph.
Explanation: This section explains the topic.
Another paragraph here.

After:

This is a normal paragraph.

Explanation: This section explains the topic.
Another paragraph here.

Steps to Use

  1. Set Up Apps Script:
    • Open Google Drive, navigate to Extensions > Apps Script, and paste the code into the script editor.
  2. Replace the Document ID:
    • Replace 'YOUR_DOCUMENT_ID_HERE' with the ID of your Google Doc.
  3. Run the Script:
    • Click the Run button in the Apps Script editor and authorize the script if prompted.
  4. Verify Changes:
    • Open your Google Doc to confirm the bolded text and added blank lines.