Remove header or other styling from an element that begins with a certain word Google Apps Script Code Snippet

To create a Google Apps Script that removes a heading in a Google Docs document if an element (paragraph) starts with a specific word from an array of words, follow these steps:

  1. Open your Google Docs document.
  2. Navigate to “Extensions” > “Apps Script”.
  3. Delete any existing code in the script editor and paste the following script:
function removeHeadingIfStartsWithWord() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();
  var triggerWords = ['SpecificWord1', 'SpecificWord2', 'SpecificWord3']; // Replace with your specific words
  
  paragraphs.forEach(function(paragraph) {
    var text = paragraph.getText();
    var firstWord = text.split(' ')[0]; // Get the first word of the paragraph
    if (triggerWords.includes(firstWord)) {
      // Check if the paragraph is a heading
      var heading = paragraph.getHeading();
      if (heading !== DocumentApp.ParagraphHeading.NORMAL) {
        // Change the heading to normal text if it starts with a specific word
        paragraph.setHeading(DocumentApp.ParagraphHeading.NORMAL);
      }
    }
  });
}
  1. Save the script with a descriptive name, such as “Remove Heading If Starts With Word”.
  2. To run the script, click the play/triangle button next to the removeHeadingIfStartsWithWord function in the Apps Script editor. You will likely need to grant permissions to the script to access your Google Docs document the first time you run it.

This script iterates through all paragraphs in your document, checks if the first word of a paragraph matches any word in the triggerWords array, and if so, checks whether the paragraph is formatted as a heading. If the paragraph is a heading and its first word matches one of the specified trigger words, the script changes the heading to normal text.

You need to replace 'SpecificWord1', 'SpecificWord2', 'SpecificWord3' with the words you want to trigger the removal of the heading format. The script currently checks for any heading level and changes it to normal text but can be adjusted to target specific heading levels or apply different formatting based on your requirements.