[ACCEPTED]-Can I color certain words in Google Document using Google Apps Script?-google-docs

Accepted answer
Score: 19

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

Surely THIS is the best answer 3 now! 8^)

This script was modified from the 2 one in this answer, and may be called from the UI (with 1 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();
}
Score: 14

This is a better solution:

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

Previous Answer:

The key is to 8 being able to reference just the words you 7 want to color.

My solution is to:

Get the 6 text of the paragraph that contains the 5 words you wish to color, remove the original 4 paragraph, then add each part of the text 3 back. As you add each part back the appendText 2 returns a reference to just the text added, you 1 then can specify its color with 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');
    }
  }
}
Score: 2

I think it's possible with the method setBackgroundColor 7 of class Text in DocumentApp : https://developers.google.com/apps-script/class_text#setBackgroundColor

You'll have 6 to retrieve your words as Text elements. In 5 order to do that you can use the find method 4 of your object Document, then to iterate 3 over the search results and use getElement. Finally, to 2 convert your Element object into a Text 1 object, you can use asText().

Hope it'll work ! ;)

Score: 0

This is available as a Google docs add-on 9 named Multi-instance Text Highlighting. Hints: At 8 first it didn't seem to work, but I closed 7 my doc and re-opened it, and then it worked. Then 6 it didn't seem to work now and then, but 5 I found out that special characters in your 4 text string can break it; I think I had 3 a + in my string and it just didn't do anything. But 2 without special characters, it works great. Really 1 helped me out.

More Related questions