我可以使用Google Apps脚本为Google文档中的某些字词添加颜色吗?

use*_*077 16 google-docs google-apps-script

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

Mog*_*dad 18

通过引入文档绑定脚本,现在可以创建从自定义菜单调用的文本突出显示功能.

当然,是现在最好的答案!8 ^)

此脚本是从本答案中的脚本修改的,可以从UI(没有参数)或脚本调用.

/**
 * Find all matches of target text in current document, and highlight them.
 *
 * @param {String} target     (Optional) The text or regex to search for. 
 *                            See Body.findText() for details.
 * @param {String} background (Optional) The desired highlight color.
 *                            A default orange is provided.
 */
function highlightText(target,background) {
  // If no search parameter was provided, ask for one
  if (arguments.length == 0) {
    var ui = DocumentApp.getUi();
    var result = ui.prompt('Text Highlighter',
      'Enter text to highlight:', ui.ButtonSet.OK_CANCEL);
    // Exit if user hit Cancel.
    if (result.getSelectedButton() !== ui.Button.OK) return;
    // else
    target = result.getResponseText();
  }
  var background = background || '#F3E2A9';  // default color is light orangish.
  var doc = DocumentApp.getActiveDocument();
  var bodyElement = DocumentApp.getActiveDocument().getBody();
  var searchResult = bodyElement.findText(target);

  while (searchResult !== null) {
    var thisElement = searchResult.getElement();
    var thisElementText = thisElement.asText();

    //Logger.log(url);
    thisElementText.setBackgroundColor(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(),background);

    // search for next match
    searchResult = bodyElement.findText(target, searchResult);
  }
}

/**
 * Create custom menu when document is opened.
 */
function onOpen() {
  DocumentApp.getUi().createMenu('Custom')
      .addItem('Text Highlighter', 'highlightText')

      .addToUi();
}
Run Code Online (Sandbox Code Playgroud)


Wee*_*oey 11

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

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

上一个答案:

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

我的解决方案是:

获取包含要着色的单词的段落文本,删除原始段落,然后添加文本的每个部分.当您添加每个部分后,appendText返回对仅添加的文本的引用,然后您可以使用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');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)