我有一個谷歌檔案,并且有幾個單詞描述、基本原理和繼承的實體,我想將它們設定為粗體。通過在這里搜索,我根據其他建議構建了這個:
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);
}
}
當我運行它時,它只會加粗 Rationale 的第一個實體。我嘗試將 if 更改為一段時間,但它只是運行并沒有完成。
有任何想法嗎?
uj5u.com熱心網友回復:
這應該做。這篇文章的學分。while 內的 laste 行是關鍵。
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)
}
}
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432772.html
