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

问题描述 投票:2回答:1

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

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

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

谢谢你的帮助!

javascript google-apps-script google-drive-sdk google-docs google-docs-api
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.