将在 google 文档中多次出现的文本字符串(例如“student 1”)替换为新的文本字符串(例如“学生A") 粗体字,分为两步:
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);
}
}
上面的黑体文本代码的灵感来自于帖子中的代码查找文本(多次)并突出显示 https://stackoverflow.com/questions/11478471/finding-text-multiple-times-and-highlighting.
字符的偏移值只是描述该字符在文档中的位置的整数,第一个字符的偏移值为 1(就像字符的坐标)。
使用“学生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");
}
在谷歌文档中,只需运行脚本 docReplace 将所有出现的“student 1”更改为“学生A” 以粗体字显示。
上述两个函数(docReplace和boldfaceText)可能是向新手(像我一样)介绍谷歌文档脚本的好方法。在使用谷歌文档脚本一段时间以熟悉之后,学习 Robin 更优雅和更高级的代码,它可以同时执行上述两个步骤。