Google 脚本:如何高亮显示一组单词?

Google Script: How to highlight a group of words?

我想为 google 文档编写一个脚本来自动突出显示一组单词。

一句话,我可以使用这样的脚本:

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

但我需要在文本中搜索一组更多的单词并突出显示它们。 (这是列表:https://conterest.de/fuellwoerter-liste-worte/

如何编写更多字的脚本?

这似乎有点太复杂了:

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

感谢您的帮助!

您可以使用嵌套 for 循环:

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

这样您就可以轻松地用更多的单词扩展数组 words