Google Apps Script that bolds elements in a Google Docs document that begin with any word


To create a Google Apps Script that bolds elements in a Google Docs document that begin with any word from a given array of words, follow these steps:

  1. Open your Google Docs document.
  2. Go to “Extensions” > “Apps Script”.
  3. Replace any code in the script editor with the following script:
function boldElementsStartingWithWords() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.getText();
var searchWords = ['Word1', 'Word2', 'Word3']; // Add your words here

searchWords.forEach(function(word) {
var searchPattern = '\b' + word + '\b'; // Word boundary to match whole word
var foundElement = body.findText(searchPattern);

while (foundElement) {
  var foundText = foundElement.getElement().asText();
  var startOffset = foundElement.getStartOffset();
  var endOffset = foundElement.getEndOffsetInclusive();

  // Apply bold formatting to the found word
  foundText.setBold(startOffset, endOffset, true);

  // Find next occurrence
  foundElement = body.findText(searchPattern, foundElement);
}

});
}
  1. Save the script with a name, for example, “Bold Start Words”.
  2. To run the script, click on the play/triangle button next to the boldElementsStartingWithWords function in the Apps Script editor. You might need to give permissions to the script to access your Google Docs document the first time you run it.

This script searches your document for each word in the searchWords array. When it finds an occurrence of any word, it applies bold formatting to that word. The script uses word boundaries (\b) in the search pattern to ensure that it matches only whole words, not parts of larger words.

Please adjust the searchWords array by replacing 'Word1', 'Word2', 'Word3' with the actual words you want to search for and bold. This script can be customized further to meet specific needs, such as applying different formatting styles or searching within specific parts of the document.