查找文本(多次)和突出显示

时间:2012-07-13 21:13:43

标签: google-apps-script

我想在Google文档中找到一个单词的所有实例并突出显示它们(或评论 - 任何事情都要突出)。我创建了以下函数,但它只找到了单词的第一个外观(在本例中为“the”)。关于如何找到该单词的所有实例的任何想法都将不胜感激!

function findWordsAndHighlight() {
var doc = DocumentApp.openById(Id);
var text = doc.editAsText();
//find word "the"
var result = text.findText("the");
//change background color to yellow
result.getElement().asText().setBackgroundColor(result.getStartOffset(),                result.getEndOffsetInclusive(), "#FFFF00");
};

4 个答案:

答案 0 :(得分:10)

我知道这是一个老人,但这是我在Google Script中为文字添加效果的方法。以下示例专门用于为文档中特定字符串的所有匹配项添加突出显示。

function highlightText(findMe) {
    var body = DocumentApp.getActiveDocument().getBody();
    var foundElement = body.findText(findMe);

    while (foundElement != null) {
        // Get the text object from the element
        var foundText = foundElement.getElement().asText();

        // Where in the Element is the found text?
        var start = foundElement.getStartOffset();
        var end = foundElement.getEndOffsetInclusive();

        // Change the background color to yellow
        foundText.setBackgroundColor(start, end, "#FCFC00");

        // Find the next match
        foundElement = body.findText(findMe, foundElement);
    }
}

答案 1 :(得分:1)

好的,链接你的代码就可以这样完成:

function findWordsAndHighlight() {
var doc = DocumentApp.openById("DocID");
var text = doc.editAsText();
var search = "searchTerm";
var index = -1;
var color ="#2577ba";
var textLength = search.length-1;

while(true)
 {
   index = text.getText().indexOf(search,index+1);
   if(index == -1)
     break;
   else text.setForegroundColor(index, index+textLength,color );
 }

};

我仍有疑问。 这段代码效果很好,但为什么我必须使用search.length-1?

答案 2 :(得分:1)

随着文档绑定脚本的引入,现在可以创建一个从自定义菜单调用的文本突出显示功能。

此脚本已从this answer中的脚本修改,可以从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();
}

答案 3 :(得分:0)

嗯,简单的javascript就足够了,

var search = searchtext;
var index = -1;

while(true)
 {
   index = text.indexOf(search,index+1);

   if(index == -1)
     break;
   else
     /** do the required operation **/
 }

希望这有帮助!