Home > OS >  Script is not highlighting all repeated words, how can I fix this
Script is not highlighting all repeated words, how can I fix this

Time:02-12

I have the below script running where it needs to search the entire google doc for specific words I have chosen and highlight them within the doc. It is currently doing this however for some repeated words it does not highlight these. How could I amend the script to ensure all words are highlighted.


function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}```

CodePudding user response:

Using this sample script and the regex, how about the following modification?

Modified script:

function highlightSentences() {
  var sentences = ["value1", "value2",,,]; // Please set your search texts.

  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const searchValue = sentences.join("|");
  var rangeElement = body.findText(searchValue);
  while (rangeElement) {
    const startOffset = rangeElement.getStartOffset();
    const endOffset = rangeElement.getEndOffsetInclusive();
    const element = rangeElement.getElement();
    const textElement = element.editAsText();
    textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
    rangeElement = body.findText(searchValue, rangeElement);
  }
}

Reference:

CodePudding user response:

Unfortunately, the findText method does only return one element, as stated in the documentation that can be read here. Nevertheless, all sentences can still be found easily using a while loop, where we keep searching for our desired sentence until the findText function does not find any more. You could adapt your code so something like:

function highlightSentences() {

  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  var sentences = ["search", "these"]; //An array of things to highlight

  for (var sentence of sentences){
    var rangeElement = body.findText(sentence);

    while (rangeElement != null) {

      var foundText = rangeElement.getElement().asText();

      var startOffset = rangeElement.getStartOffset();
      var endOffset = rangeElement.getEndOffsetInclusive();
    
      foundText.setBackgroundColor(startOffset, endOffset, "#fcfc03");

      rangeElement = body.findText(sentence, rangeElement);
    }
  }
}
  • Related