Google 文档搜索整个文档和粗体字

Google Docs Search entire document and bold words

我有一份 google 文档,其中有几个我想设置为粗体的单词 Description、Rationale 和 Inheritance。从这里搜索我根据其他建议构建了这个:

    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 更改为一段时间,但只是 运行 并且没有完成。

有什么想法吗?

这应该可以。归功于此 post。 while 中的最后一行是关键。

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);
  }
}

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

如果你想突出显示黄色的单词,这是我以前的解决方案: