How to replace the contents of several lines (lines are in different children) with "deleted" using the .replaceText() method?
Google Docs example:
https://docs.google.com/document/d/1rrcp5iR64tBzArfV8W7rnkL5joKQ5YTtyfO7f5m_wps/
I tried this, but this expression doesn't work.
var body = DocumentApp.getActiveDocument().getBody();
body.replaceText("(?s)\{.*\}", "deleted");
Example data:
Input:
...
{{
lorem ipsum
lorem ipsum
lorem ipsum
}}
...
Output:
...
deleted
...
In your situation, how about the following sample script? In the current stage, it seems that replaceText
cannot be used for multiple paragraphs. So, in this sample script, I used replaceAllText
of Google Docs API.
Before you use this script, please enable Docs API at Advanced Google services.
function myFunction() {
const replaceText = "deleted"; // This is from your question.
const doc = DocumentApp.getActiveDocument();
const matches = doc.getBody().getText().match(/\{\{[\s\S\w]+?\}\}/g);
if (!matches || matches.length == 0) return;
const requests = matches.map(text => ({ replaceAllText: { containsText: { matchCase: false, text }, replaceText } }));
Docs.Documents.batchUpdate({ requests }, doc.getId());
}
When this script is used, the following result is obtained. In this sample script, the format is kept even when the text is replaced.