I am trying to write a script that searches a Google document to find matches of words from a Google sheet(which serves as my database) and highlight them in the Google doc.
I have 3 challenges:
My script only returns the first occurrence of the words.
My script highlights the entire text instead of just one word, for example, one of the words in my sheet database is "The", I would like the script to highlight just "The" but instead it highlights "The" and the rest of the sentence in the Google doc.
I am using a for loop, but the loop breaks when there is no match, and ".getelement" returns a "can't get property of null" error.
Here is the code
for(i=0;i<array.length; i++){
var array = flatten(range).filter(text => text !== '');
var doc = DocumentApp.openById("1Ri9xOJl9rJE8HOrik0xDo5EpA0lJI7Um9tCxw8SzN28");
var body =doc.getBody();
var target = array[i];
var searchresult = body.findText(target);
var thisElement = searchresult.getElement();
var thisElementText = thisElement.asText();
thisElementText.setBold(true);
}
flatten(range)
. From the function name, I guessed that this is a function for converting multiple-dimensional arrays to 1-dimensional arrays.var array = flatten(range).filter(text => text !== ''); var doc = DocumentApp.openById("1Ri9xOJl9rJE8HOrik0xDo5EpA0lJI7Um9tCxw8SzN28"); var body =doc.getBody();
can be moved outside of the loop.thisElementText.setBold(true);
, a paragraph is used.var searchresult = body.findText(target);
. In order to search other values, it is required to search the next target.I am using a for loop, but the loop breaks when there is no match, and ".getelement" returns a "can't get property of null" error.
, in this case, I think that var searchresult = body.findText(target);
returns null
. This is the reason for your issue.When these points are reflected in your script, how about the following modification?
function myFunction() {
var range = [["sample1"], ["sample2"]]; // This is a sample value. Please set your value here.
var array = range.flat().filter(text => text !== '');
var doc = DocumentApp.openById("1Ri9xOJl9rJE8HOrik0xDo5EpA0lJI7Um9tCxw8SzN28");
var body = doc.getBody();
for (i = 0; i < array.length; i++) {
var target = array[i];
var searchresult = body.findText(target);
while (searchresult) {
var thisElement = searchresult.getElement();
var thisElementText = thisElement.asText();
thisElementText.setBold(searchresult.getStartOffset(), searchresult.getEndOffsetInclusive(), true);
searchresult = body.findText(target, searchresult);
}
}
}