I have a Google Doc (only the type like Word, not spreadsheets or anything else) where I need to iterate over a series of rules (regular expressions) and style whatever matches the rules via an add on. The main body looks like this:
function showIssues() {
var body = DocumentApp
.getActiveDocument()
.getBody();
const rules = {
fluff: {
match: '\b(just|very)\b',
color: '#FFDDDD'
},
adverbs: {
match: '(\w+ly)\b',
color: '#FF00FF'
}
};
for (const [rule, definition] of Object.entries(rules)) {
body.replaceText(definition.match, "<$1>")
.asText()
.setBackgroundColor(definition.color);
}
}
However, not only does it not replace the matched text with <matched text>
, but it also replaces the entire background, not just that of the replaced text.
I don't know Javascript well and I've never written a Google Docs add on before.
How do I match tiny snippets of text and set their attributes?
Unlike some other answers on this site, I'm not doing single replacements. Each rule might match against multiple elements in the document. Thus, I'm pretty sure I've messed this up :)
As an aside, some of these documents will be in the 100K word range, so they might be rather large.