Google Script: How to highlight a group of words?

2019-05-21 00:46发布

问题:

I'd like to write a script for google docs to automatically highlight a set of words.

For one word I could use a script like this:

function myFunction() {
  var doc  = DocumentApp.openById('ID');
  var textToHighlight = "TEST"
  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);
    }
  } 
}

But I need to search the text for a set of many more words and highlight them. (this is the list: https://conterest.de/fuellwoerter-liste-worte/)

How do I write a script for more words?

This seems to be a little bit too complicated:

function myFunction() {
  var doc  = DocumentApp.openById('ID');
  var textToHighlight = "TEST"
   var textToHighlight1 = "TEST1"
  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);
    }
  } 
  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(textToHighlight1);
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  } 
}

Thanks for your help!

回答1:

You could use a nested for loop:

var words = ['TEST', 'TEST1'];

// For every word in words:
for (w = 0; w < words.length; ++w) {

    // Get the current word:
    var textToHighlight = words[w];


    // Here is your code again:
    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);
        }
    }
}

This way you can easily extend the array words with more words.