Home > front end >  Google Docs Search entire document and bold words
Google Docs Search entire document and bold words

Time:02-24

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?

CodePudding user response:

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

CodePudding user response:

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

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

  • Related