[GAS Beginner Series #52] Replace Text in Google Docs: How to Use Body.replaceText() and Template Automation

In our previous lesson (Part 51), we took our very first step into Phase 6: Google Docs Automation by learning how to programmatically open a specific file—the “Sapporo Office Invoice Template”—using DocumentApp.openById()!

Now that you can open documents with code, the natural next step is automating the text updates: swapping out placeholders like customer names, dates, and amounts with actual data in one swift execution.

Relying on manual copy-pasting or standard find-and-replace often leads to typos and costly misdirected invoices. With Google Apps Script (GAS), however, you can accurately replace hundreds of text occurrences across your documents in seconds.

In this 52nd installment, we’ll dive deep into an essential method for bulk text replacement in Google Docs: Body.replaceText()!

Using a realistic invoice generation workflow from our Sapporo office, we’ll cover basic syntax, the classic regular expression escaping pitfall that trips up every beginner, and practical techniques to streamline your everyday office tasks.

1. What Is Body.replaceText()?

Body.replaceText() is a Google Apps Script method that searches the main text area (Body) of a Google Doc for a specific search pattern and replaces all occurrences with a replacement string.

Understanding Document Hierarchy: Document vs. Body vs. Text

Let’s briefly review how Google Docs structures its elements in GAS:

  • 【Entire Document】= Document (Retrieved via DocumentApp.openById())
  • 【Main Content Area】= Body (Retrieved via doc.getBody()) ★ Today’s star!
  • 【Text Elements & Paragraphs】= Paragraph / Text (Individual components inside the Body)
// 1. Open the document (entering the house)
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");

// 2. Access the "Body" of the document (entering the room)
var body = doc.getBody();

// 3. Batch replace text inside the body (swapping out the wallpaper/text)
body.replaceText("[OLD_TEXT]", "[NEW_TEXT]");

Why Call replaceText on Body Instead of Document?

Just like working with Google Sheets (where you target a specific sheet or range via Sheet.getRange()), Google Docs requires you to specify which container or region you want to edit.

A Google Doc contains distinct sections like the Body, Header, and Footer. When you want to modify standard paragraph text, the rule of thumb is to first grab the document’s main area using doc.getBody() and call replaceText() on that body object.

2. Why Template Replacement Is the Key to Workflow Automation

When automating Google Docs for business operations, the “Template Pattern” is by far the most reliable approach:

  1. Create a pre-formatted document with your desired layout, branding, and typography.
  2. Insert distinct placeholder tags where variables belong, such as {Client Company Name} or {Invoice Date}.
  3. Use GAS’s replaceText() to substitute placeholders with dynamic data.

Rather than programmatically assembling paragraphs, margins, and font sizes from scratch, swapping placeholder text inside a polished template document produces clean, professional documents with far less code!

3. STEP 1: Setup! Create the “Sapporo Office Invoice Template”

Let’s set up a practice document in Google Drive so we can test the script.

Instructions

  1. Open Google Drive and click “New” > “Google Docs”.
  2. Rename the document title to “Sapporo Office Invoice Template”.
  3. Paste the following template text directly into the document body:
INVOICE

To: {Client Company Name}

Thank you very much for your business.
We hereby submit the invoice details below:

----------------------------------------
Invoice Date: {Invoice Date}
Total Amount Due: {Total Amount}
----------------------------------------

■ Contact Information
Sapporo Office, Contact: Sato
  1. Check the browser address bar (URL) and copy down the Document ID.
    • Example URL: https://docs.google.com/document/d/1ABC123xyz_SampleID_456/edit
    • The long alphanumeric string between /d/ and /edit is your Document ID.

4. STEP 2: [Hands-On] Write Code to Batch Replace Text

Now that your template is ready, open the Apps Script editor and write the script.

We will automatically replace {Client Company Name}, {Invoice Date}, and {Total Amount} with actual data for a client in Sapporo!

1. Open a Standalone Script (or Container-Bound GAS)

In Google Drive, select “New” > “More” > “Google Apps Script” to open a new editor, then enter the following code (replace YOUR_DOCUMENT_ID with your copied ID):

function replaceInvoiceTemplate() {
  // 1. Open the template document by ID (Review from Part 51!)
  var docId = "YOUR_DOCUMENT_ID"; 
  var doc = DocumentApp.openById(docId);
  
  // 2. Get the body area of the document
  var body = doc.getBody();
  
  // 3. Replace placeholders with real values
  // Note: Escaping (\\) is required here!
  body.replaceText("\\{Client Company Name\\}", "Sapporo Soup Curry Honpo Co., Ltd.");
  body.replaceText("\\{Invoice Date\\}", "October 1, 2026");
  body.replaceText("\\{Total Amount\\}", "$1,540.00");
  
  // 4. Log completion message
  Logger.log("Invoice replacement completed successfully!");
}

2. Save and Run

  1. Click the Save (disk icon) at the top of the editor.
  2. Ensure replaceInvoiceTemplate is selected, then click “Run”.
  3. If this is your first execution, grant permissions via Google’s authorization prompt (refer to Part 2 for details).

3. Verify the Results

Switch back to your Google Doc to view the updated content!

INVOICE

To: Sapporo Soup Curry Honpo Co., Ltd.

Thank you very much for your business.
We hereby submit the invoice details below:

----------------------------------------
Invoice Date: October 1, 2026
Total Amount Due: $1,540.00
----------------------------------------

■ Contact Information
Sapporo Office, Contact: Sato

The curly bracket tags like {Client Company Name} and {Invoice Date} were instantly replaced with real invoice details!

5. [Crucial] The Regular Expression Escaping Trap Every Beginner Falls Into

Looking closely at our script, you might ask: “Why did we write \\{Client Company Name\\} with double backslashes instead of just {Client Company Name}?”

This is the single most common pitfall when working with Body.replaceText() and the primary reason scripts fail or throw errors!

replaceText() Treats Search Patterns as Regular Expressions (Regex)!

Under the hood, the first argument in replaceText(searchPattern, replacement) is interpreted as a JavaScript Regular Expression rather than a plain string literal.

In regular expressions, characters like {, }, (, ), [, ], ?, +, and * are reserved “metacharacters” with functional meanings.

(For instance, {1,3} represents a quantifier meaning “match 1 to 3 repetitions of the preceding character”).

If you supply raw brackets via body.replaceText("{Client Company Name}", "..."), GAS assumes you are defining a repetition quantifier, leading to runtime syntax errors or failed matches where text is completely ignored.

The Fix: Prepend Escapes with \\

To instruct GAS to treat brackets as literal characters rather than regex syntax, you must escape them.

Inside JavaScript string literals, write two backslashes—\{ and \}—to escape each brace.

Target Placeholder Code Syntax (Escaped) Explanation
{Client Company Name} "\\{Client Company Name\\}" Add \\ before { and }
[Contact Name] "\\[Contact Name\\]" Add \\ before [ and ]
(Date) "\\(Date\\)" Add \\ before ( and )

💡 Alternative: Use Custom Delimiters Like “【 】” or “% %” to Avoid Escaping

If typing \\{ every time feels tedious, consider using characters that do not carry special regex meaning, such as 【Client Company Name】 or %Client Company Name%!

// No regex escaping required when using Japanese brackets or percentage signs!
body.replaceText("【Client Company Name】", "Sapporo Soup Curry Honpo Co., Ltd.");

6. Practical Application: Batch Creating Invoices from Google Sheets

In enterprise environments, the standard automation pattern involves iterating through rows in a Google Sheet (Row 1: Dosanko Foods, Row 2: Sapporo Grand Hotel…) and generating individual invoice files for each client.

Here is an integrated example combining our Spreadsheet skills (Phases 1–2), Google Drive management (Phase 5), and Document manipulation:

function generateMultipleInvoices() {
  // 1. Prepare master template document and destination folder
  var templateId = "YOUR_TEMPLATE_DOC_ID";
  var templateFile = DriveApp.getFileById(templateId);
  var targetFolder = DriveApp.getFolderById("YOUR_FOLDER_ID"); // Output folder
  
  // 2. Fetch billing records from Google Sheets (Review of Range.getValues() from Part 13!)
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getRange("A2:C4").getValues(); // Col A: Company, Col B: Date, Col C: Amount
  
  // 3. Loop through data rows to copy templates and replace text
  for (var i = 0; i < data.length; i++) {
    var companyName = data[i][0];
    var dateText    = data[i][1];
    var amountText  = data[i][2];
    
    // Duplicate the template file (Review of File.makeCopy() from Part 44!)
    var newFile = templateFile.makeCopy("Invoice_" + companyName, targetFolder);
    
    // Open the cloned document and substitute placeholders
    var newDoc = DocumentApp.openById(newFile.getId());
    var body = newDoc.getBody();
    
    body.replaceText("【Client Company Name】", companyName);
    body.replaceText("【Invoice Date】", dateText);
    body.replaceText("【Total Amount】", amountText);
    
    // Changes persist automatically when script execution finishes
  }
  
  Logger.log("All invoice copies and replacements completed successfully!");
}

By connecting DriveApp, SpreadsheetApp, and replaceText(), administrative tasks that previously took hours can now finish flawlessly in mere seconds!

7. Top 5 Common Traps and Solutions in Body.replaceText()

Here is a breakdown of recurring errors developers encounter with Body.replaceText() and how to resolve them:

Trap 1: Calling doc.replaceText() Throws a TypeError

  • Error: TypeError: doc.replaceText is not a function
  • Cause: replaceText() belongs to the Body class, not the root Document class.
  • Solution: Always obtain the body reference first via var body = doc.getBody(); before calling body.replaceText(...).

Trap 2: Text Is Left Unchanged (Whitespace or Case Mismatch)

  • Cause: The template text contains extra spacing like { Invoice Date }, while the script looks for "{Invoice Date}" without spaces.
  • Solution: Replacement is strictly case-sensitive and spacing-sensitive. Copy the exact string from the document directly into your script.

Trap 3: Unescaped Braces Trigger “SyntaxError: Invalid regular expression”

  • Cause: Using reserved characters like {} or [] directly in the search pattern violates regex syntax rules.
  • Solution: Escape delimiters using \{, or switch to safe custom delimiters like 【Client Company Name】.

Trap 4: Overwriting the Master Template Directly

  • Cause: Running replaceText() on the master template without duplicating it first with makeCopy().
  • Solution: Overwriting destroys the original placeholders for subsequent runs! In production scripts, always create a copy with File.makeCopy() first, then run your replacements on the new file.

Trap 5: Passing Raw Numeric Values Causes Errors

  • Cause: Passing a Number directly into the replacement parameter, such as replaceText("【Amount】", 154000).
  • Solution: The second argument of replaceText() expects a string. Convert numbers first using String(154000), "" + 154000, or formatted strings like "$1,540.00".

8. Summary and What’s Next

Today, we mastered automated document editing with Body.replaceText() in Google Apps Script.

Key Takeaways

  1. Access the document body with doc.getBody() before calling body.replaceText()
  2. Using placeholder replacement inside templates is the most efficient document automation pattern
  3. Metacharacters like {} and [] require double-backslash escaping (\\)
  4. Using safe delimiters like 【Placeholder】 keeps code clean without escape sequences
  5. Ensure the replacement value is formatted as a String

You can now programmatically customize any template document with precision!

However, when generating contracts or invoices, you often need to dynamically append new clauses, wire transfer instructions, or custom notes to the very end of the file.

In Part 53, we will explore Body.appendParagraph() to add brand-new paragraphs dynamically to your Google Docs!

Mastering text appending and line insertion will give you complete control over document structure. See you in the next tutorial!