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
- Accesses the Current Document:
- Retrieves the active Google Doc.
- Loops Through All Paragraphs:
- Scans each paragraph in the document.
- Finds Heading 2 Text:
- Uses
paragraph.getHeading()
to identify paragraphs styled as Heading 2.
- Uses
- 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 Script | After Running Script |
---|---|
Introduction | 1. Introduction |
Getting Started | 2. Getting Started |
Advanced Features | 3. Advanced Features |
How to Use This Script
Step 1: Open Google Apps Script
- Open your Google Doc.
- Click on Extensions > Apps Script.
Step 2: Add the Script
- Delete any existing code in the editor.
- Copy and paste the script above.
Step 3: Run the Script
- Click the Run button (
▶
) in the Apps Script editor. - 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.
