Google Apps Script that finds elements in a Google Docs document that end with a question mark and sets them to bold

To create a Google Apps Script that finds elements in a Google Docs document that end with a question mark and sets them to bold, you can iterate through the elements of the document, identify text that ends with a question mark, and then apply bold formatting to those elements. This script focuses on paragraph elements, which are common for containing text that might end with a question mark.

Here’s how you can write a script to achieve this:

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

  paragraphs.forEach(function(paragraph) {
    var text = paragraph.getText();
    // Check if the paragraph text ends with a question mark
    if (text.endsWith('?')) {
      var textLength = text.length;
      // Apply bold formatting to the entire paragraph
      paragraph.editAsText().setBold(0, textLength - 1, true);
    }
  });
}

This script checks each paragraph to see if it ends with a question mark. If it does, it applies bold formatting to the entire text of that paragraph.

Explanation of the key parts:

  • paragraphs.forEach(function(paragraph) {...}): Iterates over each paragraph in the document.
  • if (text.endsWith('?')) {...}: Determines if the current paragraph’s text ends with a question mark.
  • paragraph.editAsText().setBold(0, textLength - 1, true): Applies bold formatting to the entire paragraph. It uses 0 as the start index and textLength - 1 as the end index to cover the whole paragraph.

How to use this script:

  1. Open your Google Docs document.
  2. Click on Extensions -> Apps Script.
  3. Delete any code in the script editor and paste the above script.
  4. Save the script with a name, for example, BoldQuestions.
  5. Run the script by clicking the play/run button. You might need to authorize the script to run under your Google account the first time.

After running the script, all paragraphs that end with a question mark in your document will be set to bold. This script can be modified or extended to handle other elements (like headings or list items) and to apply different formatting based on specific criteria.