用粗体字的新文本字符串(例如“Student A”)替换在 google 文档中出现多次的文本字符串(例如“student 1”)的简单方法,是两个步骤:
1- 编写一个函数(称为 docReplace)以常规/普通字体(无粗体)进行搜索和替换:
function docReplace() {
var body = DocumentApp.getActiveDocument().getBody();
// change "student 1" to "Student A"
body.replaceText("student 1", "Student A");
}
2- 编写一个函数(例如,boldfaceText)来搜索所需的文本(例如,“学生 A”)和该文本的两个偏移值(即 startOffset 和 endOffsetInclusive)在每次出现时将这些偏移值内的字符的字体设置为粗体:
function boldfaceText(findMe) {
// put to boldface the argument
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText(findMe);
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the Element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Change the background color to yellow
foundText.setBold(start, end, true);
// Find the next match
foundElement = body.findText(findMe, foundElement);
}
}
上面的boldfaceText 代码的灵感来自Finding text (multiple times) and highlighting 中的代码。
一个字符的偏移值只是描述该字符在文档中的位置的整数,第一个字符的偏移值为 1(它类似于字符的坐标)。
使用“Student A”作为调用函数boldfaceText的参数,即,
boldfaceText("Student A");
可以嵌入到函数docReplace中,即
function docReplace() {
var body = DocumentApp.getActiveDocument().getBody();
// change "student 1" to "Student A"
body.replaceText("student 1", "Student A");
// set all occurrences of "Student A" to boldface
boldfaceText("Student A");
}
在 google 文档中,只需运行脚本 docReplace 即可将所有出现的“student 1”更改为粗体显示的“Student A”。
上述两个函数(docReplace 和boldfaceText)可能是向新手(如我)介绍谷歌文档脚本的好方法。在使用 google doc 脚本熟悉了一段时间后,学习 Robin 更优雅、更高级的代码,它可以同时完成上述两个步骤。