-2

I'm looking for a simple script for a Google Docs add-on that will highlight words held in an array. I want the script to auto-highlight the words as I type. Is this simple enough?

Thanks!

SMcDonald
  • 105
  • 2
  • 10
  • CMD+F and just type... – RemcoE33 Oct 02 '21 at 20:25
  • But what if I have a list of 50 words I want it to look out for and highlight. And depending on what words they are, highlight them in different colours? – SMcDonald Oct 02 '21 at 20:30
  • I don't know if it is possible to highlight words as you type (except mentioned Ctrl+F). As for to highlight a given array of words it's possible. But how will you pass the words into a script? A simplest way is just to put these words inside the script as an array `var arr = ['word1', 'word2', 'word3']`. Or it can be all words of the first paragraph. Etc. You need to decide it beforehand. – Yuri Khristich Oct 02 '21 at 22:02

1 Answers1

2

Based on Can I color certain words in Google Document using Google Apps Script?

function highlight_words() {
  var doc   = DocumentApp.getActiveDocument();
  var words = ['one','two','three'];
  var style = { [DocumentApp.Attribute.BACKGROUND_COLOR]:'#FFFF00' };
  var pgfs  = doc.getParagraphs();

  for (var word of words) for (var pgf of pgfs) {
    var location = pgf.findText(word);
    if (!location) continue;
    var start = location.getStartOffset();
    var end = location.getEndOffsetInclusive();
    location.getElement().setAttributes(start, end, style);
  }
}
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23