Can I color certain words in Google Document using Google Apps Script?

后端 未结 4 2323
余生分开走
余生分开走 2020-11-30 03:44

I\'m trying to highlight certain words in my Google Document. I know I can replace text using document.replace, but it only replaces string itself, not formatting. Is there

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 04:00

    This is a better solution:

    function highlightTextTwo() {
      var doc  = DocumentApp.openById('

    Previous Answer:

    The key is to being able to reference just the words you want to color.

    My solution is to:

    Get the text of the paragraph that contains the words you wish to color, remove the original paragraph, then add each part of the text back. As you add each part back the appendText returns a reference to just the text added, you then can specify its color with setForegroundColor():

    function highlightText() {
      var doc = DocumentApp.openById('');
      var textToHighlight = 'dusty death';
      var textLength = textToHighlight.length;
      var paras = doc.getParagraphs();
      var paraText = '';
      var start;
      for (var i=0; i= 0) {
          var preText = paraText.substr(0, start);
          var text = paraText.substr(start, textLength);
          var postText = paraText.substr(start + textLength, paraText.length);
          doc.removeChild(paras[i]);
          var newPara = doc.insertParagraph(i, preText);
          newPara.appendText(text).setForegroundColor('#FF0000');
          newPara.appendText(postText).setForegroundColor('#000000');
        }
      }
    }
    

提交回复
热议问题