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

2024-06-26

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

例如,我想要“狗”的每个实例......

  • Cats
  • Dogs
  • Fish

并将“dogs”样式设置为“Heading 2”,如下所示:

  • Cats
  • Dogs

  • Fish

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


使用的方法有:

  • findText https://developers.google.com/apps-script/reference/document/body#findText(String),应用于文档正文。它找到第一个匹配项;通过将前一个匹配作为第二个参数“from”传递来找到后续匹配。搜索模式是一个以字符串形式呈现的正则表达式,在此示例中(?i)\\bdogs\\b其中 (?i) 表示不区分大小写的搜索,并且\\b正在逃避\b,意思是单词边界——所以我们不会将“hotdogs”与“dogs”一起重新设计。
  • 获取元素 https://developers.google.com/apps-script/reference/document/range-element#getElement(),应用于 findText 返回的 RangeElement。重点是,匹配的文本可能只是元素的一部分,这部分称为RangeElement。我们不能仅将标题样式应用于一部分,因此会获得整个元素。
  • 获取父级 https://developers.google.com/apps-script/reference/document/text#getparent,应用于 getElement 返回的 Text 元素。同样,这是因为标题样式适用于文本之上的级别。
  • 设置属性 https://developers.google.com/apps-script/reference/document/element#setattributesattributes具有适当的样式(预先创建的对象,使用适当的enums https://developers.google.com/apps-script/reference/document/attribute)。这适用于文本的父级,无论它是什么 - 段落、项目符号等。人们可能希望对此更有选择性,并检查元素的类型 https://developers.google.com/apps-script/reference/document/element#gettype首先,但我在这里不这样做。

例子:

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);
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Google Apps 脚本将标题样式应用到单词的所有实例 的相关文章

随机推荐