Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding text (multiple times) and highlighting

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 only finds the first appearance of the word ("the" in this case). Any ideas on how to find all instances of the word would be appreciated!

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");
};
like image 699
user1523207 Avatar asked Jul 13 '12 21:07

user1523207


3 Answers

I know this is an oldie, but here's how I add effects to text in Google Script. The example below is specifically for adding highlighting to all occurrences of a particular string in a document.

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);
    }
}
like image 189
DeviousDVS Avatar answered Nov 04 '22 08:11

DeviousDVS


Ok so, chaining your codes it could finish like this :

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 );
 }

};

I still have a doubt. This code works nice, but why I have to use search.length-1?

like image 27
Danielo515 Avatar answered Nov 04 '22 09:11

Danielo515


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();
}
like image 41
Mogsdad Avatar answered Nov 04 '22 09:11

Mogsdad