Home > Net >  How can I edit the attribute of a particular character in the body of a google doc with script?
How can I edit the attribute of a particular character in the body of a google doc with script?

Time:05-06

I'd like to change the font size of particular characters in the body of a google doc using Script. The following very simple code edits the entire body.

function myFunction() {

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
body.setFontSize(14);

}

How can I select particular characters in the body, or groups of characters, and edit the font size?

So far, I've tried everything in classes "body" and "text", but nothing seems to fit the bill. I suppose I'm looking for something like "body.setFontSize(5,7)", where the first number is an index and the second the end point for the font edit.

Thanks

CodePudding user response:

In your situation, how about the following modification? In this case, the method of setFontSize(startOffset, endOffsetInclusive, size) is used.

Modified script:

function myFunction() {
  const searchText = "sample"; // Please set the search text.

  const body = DocumentApp.getActiveDocument().getBody();
  let find = body.findText(searchText);
  while (find) {
    find.getElement().asText().setFontSize(find.getStartOffset(), find.getEndOffsetInclusive(), 14);
    find = body.findText(searchText, find);
  }
}
  • When this script is run, the text of searchText is searched and the font size of the searched text is changed to 14.

Reference:

  • Related