【问题标题】:Finding text (multiple times) and highlighting查找文本(多次)并突出显示
【发布时间】:2012-07-13 21:13:42
【问题描述】:

我想在 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");
};

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    我知道这是一个老歌,但这是我在 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      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?

      【讨论】:

        【解决方案3】:

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

        此脚本是从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();
        }
        

        【讨论】:

        • 重复回答一个非常相似的问题。见here
        【解决方案4】:

        嗯,简单的javascript就足够了,

        var search = searchtext;
        var index = -1;
        
        while(true)
         {
           index = text.indexOf(search,index+1);
        
           if(index == -1)
             break;
           else
             /** do the required operation **/
         }
        

        希望这会有所帮助!

        【讨论】:

        • 感谢您的帮助,balajiboss。不幸的是 index = text.indexOf(search,index+1);错误:在对象文本中找不到函数 indexOf。
        • indexOf 适用于字符串。您可以使用 getText() 方法以字符串形式获取文档的文本。
        猜你喜欢
        • 2019-04-29
        • 1970-01-01
        • 2016-12-15
        • 2012-09-30
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多