gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:01:46 34 4
gpt4 key购买 nike

我的 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com