使用 Google Apps 脚本将标题样式应用于字词的所有实例

Use Google Apps Script to apply heading style to all instances of a word

我在 Google 文档中使用 Google 应用程序脚本,如何编写一个函数来查找单词的所有实例并为其应用标题样式:

例如,我想要 "Dogs"...

的每个实例
  • Cats
  • Dogs
  • Fish

和样式 "dogs" 与 "Heading 2" 所以它看起来像:

  • Cats
  • Dogs

  • Fish

在Sheets上使用Find in App Scripts网上到处都是,但是在Docs中使用App Scripts的例子并不多。表格没有将文本重新格式化为标题的选项,因此没有相关示例。

使用方法是:

  • findText,应用于文档 Body。它找到第一个匹配;通过将前一个匹配项作为第二个参数 "from" 传递,可以找到后续匹配项。搜索模式是一个以字符串形式呈现的正则表达式,在本例中 (?i)\bdogs\b 其中 (?i) 表示 case-insensitive 搜索,而 \b 转义为 \b,意思是单词boundary — 所以我们不重新设置 "hotdogs" 和 "dogs" 的样式。
  • getElement,应用于 findText 返回的 RangeElement。关键是,匹配的文本可能只是元素的一部分,这部分称为 RangeElement。不能只对一部分应用标题样式,所以得到的是整个元素。
  • getParent,应用于getElement返回的Text元素。同样,这是因为标题样式适用于高于文本的级别。
  • setAttributes with the proper style (an object created in advance, using appropriate enums). This is applied to the parent of Text, whatever it happened to be - a paragraph, a bullet item, etc. One may wish to be more selective about this, and check the type of the element 首先,但我不在这里这样做。

示例:

function dogs() {
  var body = DocumentApp.getActiveDocument().getBody();
  var style = {};
  style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING2;
  var pattern = "(?i)\bdogs\b";

  var found = body.findText(pattern);
  while (found) {
    found.getElement().getParent().setAttributes(style);
    found = body.findText(pattern, found);
  }
}