Finding text (multiple times) and highlighting

前端 未结 4 1061
青春惊慌失措
青春惊慌失措 2020-12-03 12:44

I would like to find all the instances of a word in a Google doc and highlight them (or comment - anything so it stands out). I have created the following function, but it o

4条回答
  •  一个人的身影
    2020-12-03 13:20

    With the introduction of document-bound scripts, it's now possible to make a text highlighting function that's invoked from a custom menu.

    This script was modified from the one in this answer, and may be called from the UI (with no parameters) or a script.

    /**
     * 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();
    }
    

提交回复
热议问题