Reputation: 75
I'm trying to set the background color of text that is of a particular color into another color within a Google Doc file.
Essentially what I'd like to do is parse through it and as I find text that has a "x" background color, I want to change it to a "y" background color via Apps Script.
Here is the code that I've been using
function onOpen() {
DocumentApp.getUi()
.createMenu('Utilities')
.addItem('Auto-Replace', 'replaceSuits')
.addToUi();
};
function replaceSuits() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.editAsText();
var found = text.getBackgroundColor() === '#ff8c82';
var apple = body.findText(found);
while (apple) {
var elem = apple.getElement();
if (apple.isPartial()) {
var start = apple.getStartOffset();
var end = apple.getEndOffsetInclusive();
elem.setBackgroundColor(start, end, "#000000");
}
else {
elem.setBackgroundColor("#000000");
}
apple = body.findText(found, found);
}
};
I know my variables are repetitive and a bit nonsensical but it's due to the various testing that I've been doing trying to figure out why this code isn't working. My apologies in advance.
Any thoughts on how to go about this in an efficient manner?
Upvotes: 1
Views: 1108
Reputation: 201338
#ff8c82
to #000000
in the Google Document.If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
body.editAsText()
.function replaceSuits() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.editAsText();
// I modified below script.
for (var i = 0; i < text.getText().length; i++)
if (text.getBackgroundColor(i) == "#ff8c82") text.setBackgroundColor(i, i, "#000000");
}
If I misunderstood your question and this was not the direction you want, I apologize.
Upvotes: 2