Convert Paragraph to H3 in Docs with Apps Script

To modify the previous Google Apps Script so that it selects paragraphs that start with a number followed by a period (indicating a numbered list item or similar structure) and then updates those paragraphs to use the Heading 3 style, follow these steps. This script will loop through all paragraphs in a Google Document, check if they start with the specified pattern, and apply the Heading 3 style to those that match.

Here’s how the updated script looks:

function updateParagraphsToH3() {
  var documentId = 'YOUR_DOCUMENT_ID_HERE'; // Replace with your Google Document ID
  var doc = DocumentApp.openById(documentId);
  var body = doc.getBody();
  
  var paragraphs = body.getParagraphs();
  for (var i = 0; i < paragraphs.length; i++) {
    var paragraph = paragraphs[i];
    var text = paragraph.getText();
    // Check if the paragraph starts with a number followed by a period
    if (/^\d+\./.test(text)) {
      paragraph.setHeading(DocumentApp.ParagraphHeading.HEADING3);
    }
  }
  
  // Save the changes
  doc.saveAndClose();
}

Instructions:

  • YOUR_DOCUMENT_ID_HERE: Replace this with the ID of your Google Document.
  • The regular expression /^\d+\./ is used to match any string that starts with one or more digits (\d+) followed by a period (\.). This is how the script identifies paragraphs that start with a number and a period.
  • The script sets the heading of matching paragraphs to Heading 3 using paragraph.setHeading(DocumentApp.ParagraphHeading.HEADING3);.

After replacing YOUR_DOCUMENT_ID_HERE with the actual ID of your document and saving the script, you can run it by clicking the play/run button in the Google Apps Script interface. This action will prompt you for authorization if it’s your first time running the script. Grant the necessary permissions to allow the script to modify your document.

This script will automatically update all paragraphs that match the criteria (starting with a number followed by a period) to the Heading 3 style, making it easy to programmatically format your document.