Script to Bold Specific Words and Phrases in Google Docs

This script identifies specific words or phrases (e.g., Example:, Code Snippet:, Instructions:, Solution:) that constitute the entire paragraph or element in a Google Docs document and converts them to bold text.


The Script

function boldSpecificPhrases() {
const doc = DocumentApp.getActiveDocument(); // Access the active Google Doc
const body = doc.getBody(); // Get the document's body content
const paragraphs = body.getParagraphs(); // Get all paragraphs in the document

// List of phrases to bold
const phrasesToBold = ["Example:", "Code Snippet:", "Instructions:", "Solution:"];

paragraphs.forEach(paragraph => {
const text = paragraph.getText().trim(); // Get the text of the paragraph and trim whitespace
if (phrasesToBold.includes(text)) { // Check if the entire text matches one of the phrases
paragraph.editAsText().setBold(true); // Bold the entire paragraph
}
});

Logger.log("Specified phrases have been bolded.");
}

How It Works

  1. Access Paragraphs:
    • The script retrieves all paragraphs in the document using getParagraphs().
  2. Match Specific Phrases:
    • It checks if the trimmed text of the paragraph matches any phrase in the predefined list phrasesToBold.
  3. Apply Bold Styling:
    • If a match is found, the entire paragraph is bolded using setBold(true).

Usage Instructions

1. Open the Apps Script Editor

  • In your Google Docs, go to Extensions > Apps Script.

2. Add the Script

  • Paste the above code into the editor.

3. Save and Name Your Project

  • Click the save icon and name your project (e.g., BoldPhrases).

4. Run the Script

  • From the toolbar, select the boldSpecificPhrases function and click the play ▶️ button.
  • Grant the necessary permissions when prompted.

5. Verify the Changes

  • Check your document to see that the specified phrases have been bolded.

Customization Options

  1. Add More Phrases:
    • Update the phrasesToBold array with additional phrases to bold.
    javascriptCopy codeconst phrasesToBold = ["Example:", "Code Snippet:", "Instructions:", "Solution:", "Your Custom Phrase:"];
  2. Case Insensitivity:
    • To make the matching case-insensitive, convert both the paragraph text and phrases to lowercase before comparing:
    javascriptCopy codeconst text = paragraph.getText().trim().toLowerCase(); const lowerCasePhrases = phrasesToBold.map(phrase => phrase.toLowerCase()); if (lowerCasePhrases.includes(text)) { ... }
  3. Partial Matches:
    • Modify the condition to allow partial matches using .includes():
    javascriptCopy codeif (phrasesToBold.some(phrase => text.includes(phrase))) { ... }

Practical Applications

  1. Educational Content: Bold important labels like Example: and Solution: for better visibility.
  2. Technical Documents: Highlight terms like Code Snippet: to improve readability.
  3. Formatting Templates: Quickly apply consistent styling to frequently used phrases.