Reputation:
I'd like to write a script for google docs to automatically highlight a set of words.
For one word I could use a script like this:
function myFunction() {
var doc = DocumentApp.openById('ID');
var textToHighlight = "TEST"
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
var paras = doc.getParagraphs();
var textLocation = {};
var i;
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
But I need to search the text for a set of many more words and highlight them. (this is the list: https://conterest.de/fuellwoerter-liste-worte/)
How do I write a script for more words?
This seems to be a little bit too complicated:
function myFunction() {
var doc = DocumentApp.openById('ID');
var textToHighlight = "TEST"
var textToHighlight1 = "TEST1"
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
var paras = doc.getParagraphs();
var textLocation = {};
var i;
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight1);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
Thanks for your help!
Upvotes: 2
Views: 835
Reputation: 5691
You could use a nested for loop:
var words = ['TEST', 'TEST1'];
// For every word in words:
for (w = 0; w < words.length; ++w) {
// Get the current word:
var textToHighlight = words[w];
// Here is your code again:
for (i = 0; i < paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(), textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
This way you can easily extend the array words
with more words.
Upvotes: 1