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

Gists

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);
  }
}

 Share!