javascript - 使用谷歌应用脚本格式化谷歌文档中的关键字
问题描述
我正在尝试为谷歌文档制作一个谷歌应用脚本,它将所有出现的字符串以粗体样式放在文档中,例如,对于这个文本:
你好
你好
有效期
000000000000000000 你好 00000
你好你好你好
000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好
如果字符串是hello
,我希望脚本这样写:
你好
你好
有效期
000000000000000000你好00000
你好你好 你好
000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好
我做了这个代码:
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
var Style = {};
Style[DocumentApp.Attribute.BOLD] = true;
var found = body.findText("hola");
while(found != null) {
found.getElement().setAttributes(Style);
found = body.findText("hello", found);
}
但是我在运行代码后得到的是:
你好
你好
有效期
000000000000000000 你好 00000
你好你好你好
000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好
所以代码将包含字符串的所有行都加粗hello
,而不仅仅是字符串hello
有人知道我该怎么做才能只将字符串hello
而不是包含的所有行加粗hello
?
解决方案
您需要使用 getStartOffset() 和 getEndOffsetInclusive() 指定尝试编辑的文本的开始和结束。这将阻止您的脚本将整个文本块格式化为粗体。请看下面的代码:
function myFunction() {
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
var Style = {};
Style[DocumentApp.Attribute.BOLD] = true;
var found = body.findText("hello");
while(found != null) {
var foundText = found.getElement().asText();
var start = found.getStartOffset();
var end = found.getEndOffsetInclusive();
foundText.setAttributes(start, end, Style)
found = body.findText("hello", found);
}
}
推荐阅读
- python - 带有 Bigquery 的 CRUD Web 应用程序?
- java - 使用 aws lambda 的第 3 方 api 调用
- python - 出现错误 - selenium.common.exceptions.WebDriverException:消息:断开连接:在我运行 Python 脚本时收到
- javascript - 选择jquery中同名动态的这个id的值
- angular - rxJs forkJoin 不会从已完成的非空输入 Observables 中发出任何值
- oracle - 如何在也存在触发器的表中插入?
- flutter - Dart - “bool”类型的值不能分配给“bool”类型的变量
- r - 在R中的数据框中合并几乎相同的行
- python - 提高 np.where() 循环的性能
- html - 用jquery下载pdf的问题