谷歌文档搜索整个文档和粗体字



我有一个谷歌文档,有几个单词"描述"、"基本原理"one_answers"继承"的实例我想设置为粗体。通过在这里搜索,我根据其他建议构建了这个:

function searchAndReplace() {

let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();

// Set some elements to bold
let target1 = "Description"
let searchResult1 = body.findText(target1);
if (searchResult1 !== null) {
let thisElement1 = searchResult1.getElement();
let thisElement1Text = thisElement1.asText();
thisElement1Text.setBold(searchResult1.getStartOffset(), searchResult1.getEndOffsetInclusive(), true);
}
let target2 = "Rationale"
let searchResult2 = body.findText(target2);
if (searchResult2 !== null) {
let thisElement2 = searchResult2.getElement();
let thisElement2Text = thisElement2.asText();
thisElement2Text.setBold(searchResult2.getStartOffset(), searchResult2.getEndOffsetInclusive(), true);
}
let target3 = "Inheritance"
let searchResult3 = body.findText(target3);
if (searchResult3 !== null) {
let thisElement3 = searchResult3.getElement();
let thisElement3Text = thisElement3.asText();
thisElement3Text.setBold(searchResult3.getStartOffset(), searchResult3.getEndOffsetInclusive(), true);
}
}

当我运行这个程序时,它只会加粗第一个推理实例。我试着将if改为一段时间,但这只是运行,没有完成。

有什么想法吗?

这就行了。感谢这篇文章。这段时间内的最后一行是关键。

function searchAndReplace() {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
// Set some elements to bold
let target1 = "blandit"
let searchResult1 = body.findText(target1);
while (searchResult1 !== null) {
let thisElement1 = searchResult1.getElement();
let thisElement1Text = thisElement1.asText();
thisElement1Text.setBold(searchResult1.getStartOffset(), searchResult1.getEndOffsetInclusive(), true);
searchResult1 = body.findText(target1, searchResult1)
}
}
function highlight_words() {
var doc   = DocumentApp.getActiveDocument();
var words = ['Description','Rationale','Inheritance']; // <-- put your words here
var style = { [DocumentApp.Attribute.BOLD]: true };
var pgfs  = doc.getParagraphs();
for (var word of words) for (var pgf of pgfs) {
var location = pgf.findText(word);
if (!location) continue;
var start = location.getStartOffset();
var end = location.getEndOffsetInclusive();
location.getElement().setAttributes(start, end, style);
}
}

注意:与已接受的答案不同,我的代码一次更改给定数组的所有单词。

如果你想用黄色突出单词,这里是我以前的解决方案:https://stackoverflow.com/a/69420695/14265469

最新更新