google-apps-scriptsearchgoogle-docsbold

Google Docs Search entire document and bold words


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?


Solution

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