Automation of numbering Heading 2 titles using Google Apps Script in Google Docs

Here’s a Google Apps Script that scans a Google Doc, finds all Heading 2 paragraphs, and adds sequential numbering before each heading.

Apps Script Code

function numberHeading2InDoc() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var count = 1; // Start numbering from 1

for (var i = 0; i < paragraphs.length; i++) {
var paragraph = paragraphs[i];

// Check if the paragraph is Heading 2
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING2) {
var text = paragraph.getText().trim();

// Check if the heading is already numbered to prevent duplicate numbering
if (!/^\d+\.\s/.test(text)) {
paragraph.setText(count + ". " + text);
count++; // Increment the counter
}
}
}
}

How the Script Works

  1. Accesses the Current Document:
    • Retrieves the active Google Doc.
  2. Loops Through All Paragraphs:
    • Scans each paragraph in the document.
  3. Finds Heading 2 Text:
    • Uses paragraph.getHeading() to identify paragraphs styled as Heading 2.
  4. Adds Sequential Numbering:
    • Starts numbering from 1 and increases for each new Heading 2.
    • Ensures that it doesn’t double-number headings by checking if they are already numbered.

Example Before and After

Before Running ScriptAfter Running Script
Introduction1. Introduction
Getting Started2. Getting Started
Advanced Features3. Advanced Features

How to Use This Script

Step 1: Open Google Apps Script

  1. Open your Google Doc.
  2. Click on Extensions > Apps Script.

Step 2: Add the Script

  1. Delete any existing code in the editor.
  2. Copy and paste the script above.

Step 3: Run the Script

  1. Click the Run button () in the Apps Script editor.
  2. If prompted, grant permissions to allow the script to modify the document.

Why This is Useful

Automatic Numbering: No need to manually number headings.
Prevents Duplicate Numbers: Avoids adding numbers if they already exist.
Perfect for Reports & Outlines: Helps structure documents with clear numbering.