0

I have a google doc and there are several instance of the words Description, Rationale, and Inheritance that I want to set as bold. From searching here I built this from other suggestions:

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

When I run this it only bolds the first instance of Rationale. I tried changing the if to a while but that just ran and did not complete.

Any ideas?

2 Answers2

1

This should do. Credits to this post. The laste line inside the while is the key.

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)
  }
}
RemcoE33
  • 1,551
  • 1
  • 4
  • 11
1
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);
  }
}

Note: unlike the accepted answer my code changes all the words of the given array at once.

If you want to highligth the words with yellow color here is my previous solution: https://stackoverflow.com/a/69420695/14265469

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23