When working with structured documents in Google Docs, you may find yourself needing to identify paragraphs that start with a number and a period (like “121.” or “15.”) and turn them into headings while removing the leading numbers. With Google Apps Script, you can automate this task, saving time and ensuring consistency across your document.
In this guide, we’ll walk through creating a Google Apps Script that finds all paragraphs beginning with a number followed by a period, formats them as Heading 3, and removes the number and period.
Understanding the Goal
The aim is to:
- Identify paragraphs that start with a sequence of digits followed by a period (e.g., “121.” or “15.”).
- Convert these paragraphs to Heading 3 format.
- Remove the leading number and period from each paragraph.
Setting Up the Script
Before diving into the script, make sure you have a Google Document open where you want to apply this formatting.
- Open the Script Editor:
- In your Google Document, go to
Extensions
>Apps Script
. - This will open the Apps Script editor in a new tab.
- In your Google Document, go to
- Clear Any Existing Code:
- If there’s any code already present in the editor, delete it to start fresh.
- Copy and Paste the Script (below) into the editor.
Script Code
Here’s the complete Google Apps Script code to achieve our goal:
/**
* Adds a custom menu to the Google Docs UI for easy access.
*/
function onOpen() {
DocumentApp.getUi()
.createMenu('Custom Scripts')
.addItem('Convert Numbered Paragraphs to H3', 'convertNumberedParagraphsToH3')
.addToUi();
}
/**
* Finds paragraphs starting with a number and period, converts them to Heading 3, and removes the number and period.
*/
function convertNumberedParagraphsToH3() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var regex = /^\d+\.\s*/; // Regex to match a number followed by a period and optional space
var convertedCount = 0;
paragraphs.forEach(function(paragraph) {
var text = paragraph.getText();
// Check if the paragraph starts with a number and period
if (regex.test(text)) {
// Remove the number and period at the start
var newText = text.replace(regex, '');
// Set the updated text and convert the paragraph to Heading 3
paragraph.setText(newText);
paragraph.setHeading(DocumentApp.ParagraphHeading.HEADING3);
convertedCount++;
}
});
DocumentApp.getUi().alert(convertedCount + ' paragraphs have been converted to Heading 3 and updated.');
}
Explanation of the Script
onOpen
Function:- Adds a custom menu to the Google Docs interface, titled
Custom Scripts
, with an item calledConvert Numbered Paragraphs to H3
. - This menu item provides quick access to the main function.
- Adds a custom menu to the Google Docs interface, titled
convertNumberedParagraphsToH3
Function:- Objective: Finds paragraphs that start with a number and period, removes this prefix, and sets the paragraph format to Heading 3.
- Regular Expression (
regex
): The^\d+\.\s*
pattern matches any sequence of digits at the start of the text, followed by a period and optional whitespace. - Main Logic:
- Iterates through each paragraph in the document.
- For paragraphs matching the pattern, it:
- Removes the Number and Period: Uses
replace()
to delete the leading number and period. - Updates the Paragraph: Sets the new text and changes the paragraph format to
HEADING3
.
- Removes the Number and Period: Uses
- User Feedback: Displays an alert with the number of paragraphs updated.
How to Use the Script
- Save and Authorize the Script:
- Click the save icon (💾) to save the script.
- Run the
onOpen
function to add the custom menu, and authorize the script when prompted.
- Refresh the Document:
- Go back to your Google Document and refresh the page to ensure the custom menu loads.
- Run the Script:
- In the Google Docs toolbar, click on
Custom Scripts
>Convert Numbered Paragraphs to H3
. - The script will find all paragraphs starting with a number and period, remove this prefix, and convert them to Heading 3.
- In the Google Docs toolbar, click on
Example
Let’s walk through an example to see how the script works.
Before Running the Script
Suppose your document has the following paragraphs:
- “121. Important Notice for All Employees”
- “15. Review Your Account Settings”
- “This is a regular paragraph without numbering.”
After Running the Script
After running the script, these paragraphs will be converted as follows:
- Converted to Heading 3: “Important Notice for All Employees”
- Converted to Heading 3: “Review Your Account Settings”
- Unchanged: “This is a regular paragraph without numbering.”
The numbered paragraphs now have their prefixes removed and are formatted as Heading 3.
Tips and Troubleshooting
Here are a few tips to ensure the script runs smoothly:
- Custom Menu Not Appearing:
- Make sure you’ve saved and authorized the script, and then refreshed the document.
- Script Not Finding Numbered Paragraphs:
- Double-check that the paragraphs you want to convert start with a number and a period, as specified. The script will ignore any paragraphs that do not follow this format.
- Authorization Issues:
- If you encounter authorization errors, return to the Apps Script editor, run the
onOpen
function again, and reauthorize the script as prompted.
- If you encounter authorization errors, return to the Apps Script editor, run the
Advanced Enhancements
If you’d like to further enhance the script, here are some ideas:
1. Convert to Different Heading Levels Based on Number Size
You could modify the script to use different heading levels based on the number at the start of each paragraph. For example, paragraphs starting with a single-digit number could be converted to Heading 2, while those with multiple digits could be converted to Heading 3.
2. Add a Prefix or Suffix
Instead of removing the number and period, you could adjust the script to add a prefix or suffix to these paragraphs.
3. Log Converted Paragraphs to a Google Sheet
For tracking purposes, you could extend the script to log each converted paragraph (along with its original number) to a Google Sheet.
Final Thoughts
With this script, you can quickly reformat structured documents in Google Docs, saving time and ensuring consistency across your content. Whether you’re creating an organized outline, numbering sections, or just improving the readability of your document, this automation approach is a powerful addition to your workflow.
