javascript - 谷歌脚本 : How to highlight a group of words?

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

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

总而言之,我可以使用这样的脚本:

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

关于javascript - 谷歌脚本 : How to highlight a group of words?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106984/

相关文章:

使用库调试 Google 电子表格脚本

android - 如何使用 Google Drive SDK 对结果进行排序?

php - 使用纯 PHP 在现有的 Google 电子表格中插入行

ios - iOS 中的 Google 云端硬盘 SDK

google-apps-script - 编写附加 list 文件

javascript - 如何完成 For 循环以从一张纸中的列表中设置另一张纸中的值?

javascript - 如何解决条件下拉问题

javascript - .show() 上的 jQuery 与 LinkedIn : content is not displayed

javascript - 仅在按钮具有特定值属性时执行一些代码

javascript - 错误: inject Angular $http service into requires plugin