Apps Script example · 5 min read

Replace {{placeholders}} in an Existing Google Doc: Copy-Paste Apps Script Pattern

Working replace {{placeholders}} in an existing google doc example in Apps Script—copy-paste code, common mistakes, and when to get it built professionally.

DocsText replacement

A single Doc used as a recurring status report or letter template often needs the same few values updated every time it is reused, which is a natural fit for a short replacement script.

This tutorial focuses narrowly on the body.replaceText call itself, showing how regex-based replacement works, how to escape special characters in your tokens, and how to replace several values in one pass.

Unlike the template-copying tutorial, this script edits a document in place rather than duplicating it first, which suits recurring documents like a weekly report that gets refreshed rather than multiplied.

You will also see how to confirm each placeholder was actually found and replaced, since replaceText silently does nothing when a token is not present in the body.

Need this built? Hire a Google Apps Script developer →

Sheet / project setup

ResourceName / valuePurpose
DocumentDOC_IDOpened with DocumentApp
Token{{Company}}replaceText pattern
ValueAcme CorpReplacement string

What It Does

The script opens a Doc by ID, retrieves its body, and calls replaceText once per placeholder, passing a regex-escaped token pattern and the corresponding replacement value.

After all replacements run, the script re-scans the body for any remaining double-curly-brace pattern and logs a warning listing tokens that were never matched, so nothing gets silently missed.

Prerequisites

Placeholders in the target document should use a consistent, distinctive format such as {{FieldName}} so the regex pattern used for detecting leftover tokens does not accidentally match ordinary curly braces elsewhere in the text.

Since replaceText treats its first argument as a regular expression, know in advance if any of your token names contain characters like parentheses that would need escaping.

Walkthrough

Set DOC_ID to the target document and fill in the REPLACEMENTS object with token names mapped to their real values, then paste the replacePlaceholders function into the script editor.

Run the function once and open the document to confirm every placeholder was swapped for its real value with formatting such as bold or font size preserved around the replaced text.

Check the Apps Script execution log for the leftover-token warning to catch any placeholder you forgot to include in the REPLACEMENTS object.

Edge Cases

A placeholder that appears twice in the same document, such as a client name mentioned in both the header and the body, is replaced everywhere it occurs since replaceText is a global operation on the body.

Curly braces used for something other than a placeholder, like a code snippet pasted into the Doc, could be mistaken for a leftover token by the warning scan, so review that log message rather than assuming it is always a genuine miss.

Testing

Add a duplicate placeholder in two different paragraphs, run the script, and confirm both locations were updated identically after a single call to replaceText.

Remove one key from the REPLACEMENTS object temporarily, run the script, and confirm the warning log correctly names the placeholder that was left untouched in the document.

Hardening

Escape any regex special characters in token names dynamically with a small helper function rather than assuming every token will only ever contain letters and numbers.

Take a copy of the document with makeCopy before running replacements on an important recurring file, so a mistaken token or bad value can be undone by discarding the copy instead of manually reverting text.

Variations

Read the REPLACEMENTS values from a row in a spreadsheet instead of hardcoding them, which turns this single-document script into a lightweight mail-merge style tool.

Extend the scan to also check table cells and headers separately if you need more granular reporting on where a specific placeholder was actually found and replaced.

replacePlaceholders.gs

replacePlaceholders escapes each token key, replaces it throughout an existing document's body, and logs any double-curly-brace pattern that was never matched.

// Replace {{placeholder}} tokens in an existing Google Doc
function replacePlaceholders() {
  var DOC_ID = 'REPLACE_WITH_DOC_ID';
  var REPLACEMENTS = {
    ClientName: 'Acme Co',
    ReportDate: '2026-07-16',
    PreparedBy: 'Operations Team'
  };

  var doc = DocumentApp.openById(DOC_ID);
  var body = doc.getBody();

  for (var key in REPLACEMENTS) {
    var escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    var pattern = '\\{\\{' + escapedKey + '\\}\\}';
    body.replaceText(pattern, REPLACEMENTS[key]);
  }

  var remaining = body.getText().match(/\{\{[^}]+\}\}/g);
  if (remaining) {
    Logger.log('Warning: unmatched placeholders remain: ' + remaining.join(', '));
  }

  doc.saveAndClose();
}
  1. Line 14: Escaping regex special characters in the key means a token name containing something like a parenthesis still matches literally instead of being treated as regex syntax.
  2. Line 15: Building the pattern with escaped curly braces ensures replaceText looks for the literal double-brace token rather than treating braces as a regex quantifier.
  3. Line 16: replaceText is called once per key, so every occurrence of that specific token anywhere in the body gets updated in a single pass.
  4. Line 19: Scanning the body's text after all replacements finish is how the script detects any placeholder that never got a matching entry in REPLACEMENTS.
  5. Line 21: Logging the leftover tokens by name turns a silent gap into a visible warning you can act on before treating the document as finished.

Deploy this example

  1. 01

    Open Apps Script

    In the bound spreadsheet: Extensions → Apps Script. For standalone projects, create one at script.google.com and link your Sheet by ID.

  2. 02

    Paste and save

    Add a .gs file, paste the code below, rename constants at the top (sheet names, column letters, API property keys), then save.

  3. 03

    Authorize once

    Run the main function from the editor. Accept OAuth scopes when prompted — triggers cannot run until authorization succeeds once.

  4. 04

    Add the trigger

    Triggers → Add trigger → choose the handler function and event (time-driven, on edit, or on form submit). Delete test triggers before production.

Before you run: replace text in doc

  • 1Placeholders in the target Doc use a consistent, distinctive format
  • 2REPLACEMENTS object filled in with all expected tokens and values
  • 3Backup copy of the document taken before the first real run
  • 4Function run once and document reviewed for correct substitutions
  • 5Execution log checked for leftover-token warnings
  • 6Duplicate placeholder occurrences confirmed to update everywhere

Frequently asked questions

It edits the existing document in place, unlike the copy-template-doc tutorial, which duplicates the file first.

The script escapes each key automatically before building the search pattern, so tokens with characters like parentheses still match correctly.

The script re-scans the body for any remaining double-curly-brace pattern after all replacements and logs a warning listing anything left over.

Yes, that turns this single-document script into a lightweight mail merge, as suggested in the variations section.

Yes, replaceText operates on the whole document body, which includes table cells.

The loop simply finds no matches for each token and the leftover-token check reports nothing unusual, so nothing changes in the document.

Related examples

Want this wired into your real workflow?

I adapt these patterns to your Sheet structure, APIs, and triggers — deployed in your Google account. Fixed-scope quotes from $500 · free 30-min consult · quote within 24 hours.