Bold Text that starts with this word in a paragraph

To create a Google Apps Script that bolds the start of a paragraph if it starts with “code”, “explanation”, or “objective”, and only bolds the first word while leaving the remaining content intact, you can follow the steps below. This script will iterate through all the paragraphs in the document, check if they start with any of the specified words, and apply the bold formatting to the first word if the condition is met.

function boldFirstWordBasedOnCriteria() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();

  paragraphs.forEach(function(paragraph) {
    var text = paragraph.getText();
    var words = text.split(' ');
    if (words.length > 0) {
      // Check if the paragraph starts with one of the specified words
      var firstWord = words[0].toLowerCase(); // Convert to lowercase for case-insensitive comparison
      if (firstWord === 'code' || firstWord === 'explanation' || firstWord === 'objective') {
        // Apply bold formatting to the first word
        paragraph.editAsText().setBold(0, firstWord.length - 1, true);
      }
    }
  });
}

To use this script:

  1. Open your Google Doc.
  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 you’ll remember.
  5. Run boldFirstWordBasedOnCriteria function by clicking on the play button next to the function name or through a custom menu that you might add via Script.

This script works by checking each paragraph to see if it starts with “code”, “explanation”, or “objective” (case-insensitive). If the condition is met, it applies bold formatting to just the first word of the paragraph. Note that the script uses a simple text comparison, so it’s important that the targeted words are exactly at the beginning of the paragraph and followed by a space for the script to work as expected.

Remember, when you run this script for the first time, Google will prompt you to authorize the script to access your document. Follow the prompts to grant the necessary permissions.