google-apps-scriptgoogle-docs

How to format color of text


I would to like to write a script to find all specific words and format their color.

I tryied the following, but it seems it is not working:

function ChangeColor() {
  var body = DocumentApp.getActiveDocument().getBody();
  var myword = body.findText("var");

  while (myword !== null){
    var mysearch = myword.getElement().asText().setForegroundColor('#DC64DC');
  }
}

Can anyone help me, please?


Solution

  • You want to change the font color of "var" in the document. If my understanding is correct, how about this modification?

    Modification points :

    Modified script :

    function ChangeColor() {
      var searchValue = "var";
      var body = DocumentApp.getActiveDocument().getBody();
      var myword = body.findText(searchValue);
    
      while (myword) {
        var mysearch = myword.getElement().asText()
        mysearch.setForegroundColor(
          myword.getStartOffset(), // startOffset
          myword.getEndOffsetInclusive(), // endOffsetInclusive
          '#DC64DC' // color
        );
        var myword = body.findText(searchValue, myword); // Search next word
      }
    }
    

    References :

    If I misunderstand your question, I'm sorry.