Light
Light

Reputation: 75

How to search for text in a google document by background color?

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

Answers (1)

Tanaike
Tanaike

Reputation: 201338

  • You want to modify the background color of the text from #ff8c82 to #000000 in the Google Document.
  • You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification point:

  • In your case, the color is modified by checking the color from the text object retrieved by body.editAsText().

Modified script:

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");
}

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 2

Related Questions