Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created September 25, 2021 05:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/7fc15c4e8ecccbedd469d8d778880834 to your computer and use it in GitHub Desktop.
Save tanaikech/7fc15c4e8ecccbedd469d8d778880834 to your computer and use it in GitHub Desktop.
Replacing Template Texts with Array in Google Document using Google Apps Script

Replacing Template Texts with Array in Google Document using Google Apps Script

This is a sample script for replacing the template texts with an array in Google Document using Google Apps Script. This is for Google Apps Script of this report.

The sample input and output situations are as follows.

In the current stage, when replaceAllText of Docs API is used with the sample value of ["updated text 1", "updated text 2", "updated text 3"], all values of {{oldText}} are replaced with the 1st value of updated text 1 in one batch request. So in order to replace each {{oldText}} with ["updated text 1", "updated text 2", "updated text 3"], it is required to use a workaround. So I proposed this report.

But, when Google Apps Script is used, the script will be a bit simpler.

Sample script

function myFunction() {
  const sample = ["updated text 1", "updated text 2", "updated text 3"];
  const searchText = "{{oldtext}}";
  const documentId = "###"; // Please set your document ID.

  const body = DocumentApp.openById(documentId).getBody();
  let search = body.findText(searchText);
  let count = 0;
  while (search) {
    var text = search.getElement().asText();
    if (sample[count]) {
      text.replaceText(searchText, sample[count]);
      count++;
    } else {
      break;
    }
    search = body.findText(searchText, search);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment