Google Apps Script to combine paragraph content with a heading H3 in a Google Docs document

Creating a Google Apps Script to combine paragraph content with a heading (H3) in a Google Docs document involves writing a script that iterates through the document’s elements, identifies the H3 headings, and then merges the following paragraphs with these headings.

Here’s a basic script to get you started:

function combineH3WithParagraphs() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var elements = body.getNumChildren();
  var i = 0;

  while (i < elements) {
    var element = body.getChild(i);
    // Check if the element is a heading of type H3
    if (element.getType() === DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getHeading() === DocumentApp.ParagraphHeading.HEADING3) {
      var h3Text = element.asParagraph().getText();
      var nextElement = body.getChild(i + 1);

      // Check if the next element is a normal paragraph
      if (nextElement && nextElement.getType() === DocumentApp.ElementType.PARAGRAPH && nextElement.asParagraph().getHeading() === DocumentApp.ParagraphHeading.NORMAL) {
        var paragraphText = nextElement.asParagraph().getText();
        // Combine H3 text with the paragraph text
        element.asParagraph().setText(h3Text + " " + paragraphText);
        // Remove the original paragraph
        body.removeChild(nextElement);
        elements--; // Update the elements count as one is removed
      } else {
        i++; // Move to the next element
      }
    } else {
      i++; // Move to the next element
    }
  }
}

How to Use This Script

  1. Open your Google Docs document.
  2. Go to Extensions > Apps Script.
  3. Delete any code in the script editor and paste the above script.
  4. Save and name your project.
  5. Run the function combineH3WithParagraphs from the Apps Script editor. The first time you run it, you’ll need to authorize the script.
  6. Return to your document and you’ll see that any paragraph immediately following an H3 heading has been merged with it.

Important Notes

  • This script will combine each H3 heading with the immediately following paragraph, if it’s a normal paragraph.
  • The script does not combine subsequent paragraphs or handle complex scenarios (like lists or tables after the H3 heading).
  • Always test scripts like these on a copy of your document to prevent accidental data loss.