Google Docs Apps Script Find and Replace with Italics

548 Views Asked by At

Is there a code for google apps script that finds and replaces a specific word with the italic version in a document?

1

There are 1 best solutions below

0
On

Try this -

Sample text:

but also the leap into electronic typesetting, remaining essentially unchanged. It

but also the leap into electronic typesetting, remaining essentially unchanged. It

but also the leap into electronic typesetting, remaining essentially unchanged. It

The following code with change the word 'unchanged' to Italics -

function myFunction() {
  var wordToReplace = 'unchanged';
  var body = DocumentApp.getActiveDocument().getBody();
  toIta(wordToReplace, body);
}

function toIta(wordToReplace, body) {
  var findTextElm = body.findText(wordToReplace);
  while (findTextElm != null) {
    var text = findTextElm.getElement().asText();
    var start = findTextElm.getStartOffset();
    var end = findTextElm.getEndOffsetInclusive();
    text.setItalic(start, end, true);
    findTextElm = body.findText(wordToReplace, findTextElm);
  }
}

Hope this helps.