Updating a Paragraph in a Google Doc to an H4 Heading Using Google Apps Script

Google Apps Script is a powerful tool that allows you to automate tasks across Google Workspace applications. In this blog post, we’ll walk through how to use Apps Script to update a specific paragraph in a Google Doc that contains only the words “Multiple Choice Questions” and change its formatting to an H4 heading.

Step-by-Step Guide

  1. Open Google Apps Script:
  2. Write the Script:
    • Below is the script to find and update the paragraph containing “Multiple Choice Questions” to an H4 heading in your Google Doc.
function updateParagraphToH4() {
// Replace with the ID of your Google Doc
var docId = 'YOUR_DOC_ID_HERE';
var doc = DocumentApp.openById(docId);
var body = doc.getBody();
var paragraphs = body.getParagraphs();

// Iterate through each paragraph in the document
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
// Check if the paragraph text starts with "Multiple Choice Questions"
if (text.startsWith('Multiple Choice Questions')) {
// Set the paragraph heading to H4
paragraphs[i].setHeading(DocumentApp.ParagraphHeading.HEADING4);
Logger.log('Updated paragraph to H4: ' + text);
}
}
}

  1. Customize the Script:
    • Replace 'YOUR_DOC_ID_HERE' with the actual ID of your Google Doc. You can find this ID in the URL of your document (it’s the long string of characters between /d/ and /edit).
  2. Run the Script:
    • Save your script and click the play button (Run) to execute it. You might be prompted to authorize the script to access your Google Docs.
  3. Verify the Changes:
    • Open your Google Doc and check if the paragraph containing “Multiple Choice Questions” has been updated to an H4 heading.

Explanation of the Script

  • DocumentApp.openById(docId): Opens the Google Doc with the specified ID.
  • getBody(): Retrieves the body of the document.
  • getParagraphs(): Retrieves all the paragraphs in the document.
  • getText(): Gets the text of a paragraph.
  • setHeading(DocumentApp.ParagraphHeading.HEADING4): Sets the paragraph’s heading to H4.

This script is a simple yet effective way to automate the task of updating specific paragraphs in your Google Docs. You can modify it further to suit your needs, such as updating multiple paragraphs or changing different types of formatting.

Conclusion

With Google Apps Script, you can automate and streamline many of your Google Docs tasks. This guide showed you how to update a paragraph containing specific text to an H4 heading. Experiment with other features of Google Apps Script to enhance your productivity even further.