我正在尝试为 google docs 制作一个 google 应用程序脚本,该脚本将所有出现的字符串以粗体样式放在文档中,例如,对于此文本:
<块引用>你好
你好
不错
000000000000000000 你好 00000
你好你好你好
00000000000000001111111111111111111111112222222222222222222233333333333333333333333333333333333344444444444444444444444444444445454554545454545454545454545454545454545454545454
如果字符串是hello
,我希望脚本这样写:
你好
你好
不错
000000000000000000 你好 00000
你好你好 你好
0000000000000000111111111111111111111111222222222222222222222333333333333333333333333333333333333444444444444444444444444444444444444444444444444444444444445454545445454545445454544444454545454545454545454454
我做了这个代码:
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
你好你好你好
00000000000000001111111111111111111111112222222222222222222233333333333333333333333333333333333344444444444444444444545454545454545454545454545454545454545454545454454545444444444444454444454444444444466666666了
因此代码将包含字符串 有人知道我该怎么做才能仅将字符串 hello
的所有行加粗,而不仅仅是字符串 hello
hello
加粗而不是包含 hello
的所有行?
答案 0 :(得分:0)
您需要使用 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);
}
}