Google Script:如何突出显示一组单词?

时间:2016-01-30 20:54:05

标签: javascript google-apps-script google-drive-api google-docs google-docs-api

我想为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);
    }
  } 
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套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