google-apps-script - 在 replaceText() 中格式化

标签 google-apps-script google-docs

我的 doc.getBody().replaceText(oldregex,newstring) 目前在 Google Document 脚本中运行良好,并希望在 newstring 上设置一些粗体/斜体。这看起来比我想象的要难。有没有人找到一个整洁的方法来做到这一点?

我目前认为我需要...

  • 使用 rangeBuilder 将新文本构建为一个范围
  • 找到旧文本并将其选为范围(不知何故...)
  • 清除旧文本范围并在查找位置插入新文本范围

对于使用类似 HTML 的标签来说微不足道的事情,这似乎需要大量工作。我肯定错过了什么。非常感谢任何建议。

最佳答案

由于 replaceText 仅更改纯文本内容,保留格式,因此可以通过在替换之前应用格式来实现目标。首先,findText 遍历文本并为每个匹配项设置粗体;然后 replaceText 执行替换。

有两种情况需要考虑:仅匹配元素中的部分文本(这是典型的)和匹配整个元素。 RangeElement 类的属性 isPartial 区分了这些。

function replaceWithBold(pattern, newString) {
  var body = DocumentApp.getActiveDocument().getBody();
  var found = body.findText(pattern);
  while (found) {
    var elem = found.getElement();
    if (found.isPartial()) {
      var start = found.getStartOffset();
      var end = found.getEndOffsetInclusive();
      elem.setBold(start, end, true);
    }
    else {
      elem.setBold(true);
    }
    found = body.findText(pattern, newString);
  }
  body.replaceText(pattern, newString);
}

This seems like a lot of work for something that would be trivial

这对于使用 Apps 脚本处理 Google 文档来说既正确又典型。

关于google-apps-script - 在 replaceText() 中格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305428/

相关文章:

javascript - 如何获取列表框中所选项目的索引并使用按钮添加到列表框二?

javascript - Google Sheet 自定义函数返回 0

curl:谷歌电子表格为 .csv

java - Google Docs 的 Google API,请求文档列表 -- 400 Bad Request

google-docs - 如何以编程方式获取 google 文档演示文稿的查看 url?

google-apps-script - 在 Google Analytics 中跟踪 Google 表格

google-apps-script - 无法检索下一个对象 : iterator has reached the end error when iterating over shared Drive

google-apps-script - 是否可以使用 Apps 脚本添加归因于 Google 文档中特定文本的评论?

google-apps-script - "Cannot call DocumentApp.getUi() from this context"错误

google-apps-script - 将脚本插入多个Google Spreadsheets