在 replaceText() 中格式化

Formatting in replaceText()

我现在 doc.getBody().replaceText(oldregex,newstring) 在 Google 文档脚本中工作正常,并希望在新字符串上设置一些 bold/italic。这看起来比我想象的要难。有没有人找到一个整洁的方法来做到这一点?

我目前认为我需要...

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

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

有两种情况需要考虑:仅匹配元素中的部分文本(这是典型的)和匹配整个元素。 RangeElementclass的属性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 文档来说既正确又典型。