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
- Target Paragraphs:
- The script iterates through all paragraphs in the document using
getParagraphs()
.
- Check for “Explanation:”:
- It checks if the paragraph starts with “Explanation:” using
text.startsWith("Explanation:")
.
- Bold the Text:
- The script identifies the start and end indices of the word “Explanation:” and uses
editAsText().setBold()
to bold the text.
- Insert Blank Line:
- A blank line is inserted above the paragraph using
body.insertParagraph(i, "")
.
- 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
- Set Up Apps Script:
- Open Google Drive, navigate to Extensions > Apps Script, and paste the code into the script editor.
- Replace the Document ID:
- Replace
'YOUR_DOCUMENT_ID_HERE'
with the ID of your Google Doc.
- Run the Script:
- Click the Run button in the Apps Script editor and authorize the script if prompted.
- Verify Changes:
- Open your Google Doc to confirm the bolded text and added blank lines.
Related