1

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?

abrahamwl
  • 35
  • 1
  • 3
  • Have you checked [this](http://stackoverflow.com/questions/12064972/can-i-color-certain-words-in-google-document-using-google-apps-script/16924466#16924466)? – Sangbok Lee Mar 11 '17 at 08:28
  • Thanks, but that changes the formatting on existing text. It doesn't change existing text while keeping the formatting, which is what I want to do. – abrahamwl Mar 11 '17 at 14:12
  • Before replacing the text, store its format to a temporary variable. And after replacing, set its format with the temporary variable. – Sangbok Lee Mar 11 '17 at 17:10
  • This would work, except that there seems to be a bug in Google Apps Script (last I checked) that prevents you from either setting or reading all format information (I can't remember which). – abrahamwl Jun 25 '17 at 17:11

1 Answers1

1

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");
}
mshcruz
  • 1,967
  • 2
  • 12
  • 12