Search code examples
google-apps-scriptgoogle-docs

Google Apps Script: How do I change text in a Google Doc without altering the formatting of that text?


In Google Apps Script, how do I change text in a Google Doc without altering the formatting of that text?

For example, suppose I have some text like this: "The quick brown fox". And I want to change "quick" to "slow" and "brown" to "pink", but in all cases I want the format to be maintained, so that it comes out like "The slow pink fox". How can I do that in the general case?


Solution

  • One way to do it is to use the replaceText() method, which preserves the formatting of the text.

    This example uses Body, but the Paragraph class also has the same method:

    function changeTextButKeepFormat() {
      let body = DocumentApp.getActiveDocument().getBody();
      body.replaceText("quick", "slow");
      body.replaceText("brown", "pink");
    }