Replacing Multiple Paragraphs on Google Document with a Regex using Google Apps Script

Gists

This is a sample script for replacing the multiple paragraphs on Google Document with a regex using Google Apps Script. There is the method of replaceText(searchPattern, replacement) for replacing the text on Google Document. Ref For example, when a text of sample1 is replaced with sample2, this can be achieved by a script like DocumentApp.getActiveDocument().getBody().replaceText("sample1", "sample2"). But, when the texts for replacing are the multiple paragraphs, this script cannot be used. Namely, it is considered that in the current stage, replaceText cannot be used for replacing the multiple paragraphs. In this post, I would like to introduce a sample script for replacing the texts with the multiple paragraphs using Google Apps Script.

Sample situation

Input

The sample input situation is as follows.

Replacing Multiple Paragraphs on Google Document with a Regex using Google Apps Script

In this sample script, the texts from sample1 to sample3 are replaced to a text of REPLACED as follows.

Output

Replacing Multiple Paragraphs on Google Document with a Regex using Google Apps Script

When this output image is seen, it is found that the text style is not changed before and after the replace.

Sample script

The sample script for achieving the above situation is as follows. In this case, Google Docs API is used. When Google Docs API is used, the multiple paragraphs can be replaced. So, please enable Google Docs API at Advanced Google services.

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const matches = doc
    .getBody()
    .getText()
    .match(/sample1[\s\S\w]+?sample3/g);
  if (!matches || matches.length == 0) return;
  const requests = matches.map((text) => ({
    replaceAllText: {
      containsText: { matchCase: false, text },
      replaceText: "REPLACED",
    },
  }));
  Docs.Documents.batchUpdate({ requests }, doc.getId());
}

Note

Reference

 Share!