Search code examples
google-apps-scriptgoogle-docsgoogle-docs-api

How to replace the contents of several lines with "deleted" using the .replaceText() method?


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
...

Solution

  • 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.

    Sample script:

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

    Testing:

    When this script is used, the following result is obtained. In this sample script, the format is kept even when the text is replaced.

    From:

    enter image description here

    To:

    enter image description here

    References: