'Script is not highlighting all repeated words, how can I fix this
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");
}
}
});
}```
Solution 1:[1]
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);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oriol Castander |
