Bold words in your Doc using Google Apps Script

Creating an Apps Script to search a Google Document for elements (like text) that start with a particular word or set of words and then updating those words to be bold requires using Google Apps Script’s Document service. Here’s a step-by-step guide to creating such a script:

  1. Open Google Apps Script: Go to Google Apps Script and start a new project.
  2. Name Your Project: For clarity, name your project something relevant, like “Bold Specific Words in Doc”.
  3. Replace the Code: In the script editor, replace the contents of the default Code.gs file with the following script. This script defines a function that searches through a Google Document for the specified words and makes them bold.
function makeWordsBold() {
  var docId = 'YOUR_DOCUMENT_ID_HERE'; // Replace with your Google Doc ID
  var wordsToBold = ['Word1', 'Word2', 'Word3']; // Add the words you want to search and bold
  
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();
  
  wordsToBold.forEach(function(word) {
    var searchResult = body.findText(word);
    while (searchResult) {
      var foundElement = searchResult.getElement();
      var foundText = foundElement.asText();
      
      // Calculate the offset in case the found text is part of a larger element
      var startOffset = searchResult.getStartOffset();
      var endOffset = searchResult.getEndOffsetInclusive();
      
      // Apply bold formatting only if the word is at the beginning of the element or follows a space (to avoid partial matches)
      if (startOffset === 0 || foundText.getText().charAt(startOffset - 1) === ' ') {
        foundText.setBold(startOffset, endOffset, true);
      }
      
      // Search for the next occurrence
      searchResult = body.findText(word, searchResult);
    }
  });
  
  // Save the changes
  doc.saveAndClose();
}
  1. Update Script with Your Document ID and Words:
    • Replace 'YOUR_DOCUMENT_ID_HERE' with the actual ID of your Google Document. You can find the ID in the document’s URL.
    • Replace 'Word1', 'Word2', 'Word3' with the words you want to search for and make bold. Add or remove words from the wordsToBold array as needed.
  2. Save and Run the Script: After making the necessary replacements, save your script. You may need to authorize the script to interact with your Google Docs. Follow the prompts to grant the necessary permissions.
  3. Check Your Document: Open your Google Document to see the changes. The specified words that appear at the beginning of any text element or after a space should now be bold.

This script only applies to text elements and assumes that the words you’re looking for do not span multiple text elements. Adjustments might be necessary for more complex scenarios, such as handling words that cross element boundaries or are part of a larger formatting structure.