I’m working on a Google Apps Script project for a Google Doc that has numbered Heading2 elements. These headings use a custom prefix "Section " and look like this:
Section 1. Sample Title
Section 2. Another Title
The document also contains other Heading2 elements that don’t have this numbering format. I need to identify only the numbered ones with the “Section” prefix.
My current approach isn’t working:
if (element.getHeading() === DocumentApp.ParagraphHeading.HEADING2) {
const titleText = element.getText();
// Try to match "Section" with number
const sectionMatch = /section\s+(\d+)/i.exec(titleText);
if (sectionMatch) {
sectionNumber = parseInt(sectionMatch[1], 10);
imageCounter = 0;
chartCounter = 0;
}
}
The problem is that titleText only returns “Sample Title” without the "Section 1. " part. The numbered list prefix doesn’t appear in the text content. How can I access the actual list number and prefix from a numbered Heading2 paragraph in Google Docs? I need sectionNumber to equal the actual number from the list formatting.
Had this exact problem last month. Google Docs stores list numbering separately from the actual text, which is annoying. Here’s what worked: use getParagraphStyle() with the list properties to catch numbered paragraphs, then keep your own counter while looping through the document. When you hit a Heading2 with list formatting, check the list attributes to see if it’s numbered, then manually track where you are in that list. The annoying part is when numbering restarts or gets broken up by other stuff. I ended up making a map that tracks each list ID and its current count - only increment when you find numbered items that are actually consecutive at the same level.
Google Docs handles the numbering prefix through its list formatting system - it’s not actual text content. You’ll need to work with the list properties to reconstruct what you see visually. Use getAttributes() on the paragraph element to check for list formatting, then combine it with getListId() to identify which numbered list it belongs to. You’ll have to manually track list items as you iterate through document elements. Keep a counter for each list ID and increment it when you find consecutive paragraphs with matching list properties. That’s how you can figure out the actual section number even though it doesn’t show up in the text.
yeah, this is tricky since google docs separates numbering from the actual text. you’ll need to check the paragraph’s list properties with getListId() and getNestingLevel() instead of parsing the text directly. the numbering won’t show up in getText().