我可以使用 Google Apps Script 为 Google 文档中的某些词着色吗?

我可以使用 Google Apps Script 为 Google 文档中的某些词着色吗?

问题描述:

我正在尝试突出显示我的 Google 文档中的某些字词.我知道我可以使用 document.replace 替换文本,但它只替换字符串本身,而不是格式.有没有办法使用 Google Apps 脚本用彩色字符串替换字符串?

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 a way to replace string with colored string using Google Apps Script?

这是一个更好的解决方案:

This is a better solution:

function highlightTextTwo() {
  var doc  = DocumentApp.openById('<your document id');
  var textToHighlight = 'dusty death';
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;

  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(textToHighlight);
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  }
}

上一个答案:

关键是能够仅引用您想要着色的单词.

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

我的解决方案是:

获取包含您要着色的单词的段落文本,删除原始段落,然后将文本的每一部分添加回去.当您将每个部分添加回来时,appendText 仅返回对添加的文本的引用,然后您可以使用 setForegroundColor() 指定其颜色:

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('<your document id>');
  var textToHighlight = 'dusty death';
  var textLength = textToHighlight.length;
  var paras = doc.getParagraphs();
  var paraText = '';
  var start;
  for (var i=0; i<paras.length; ++i) {
    paraText = paras[i].getText();
    start = paraText.indexOf(textToHighlight);
    if (start >= 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');
    }
  }
}