Google Docs – How to Automate Find & Replace to Change Font Colors

google docsgoogle-apps-script

How can I automate a find & replace function to change the font colour of all suit symbols document wide?

I write bridge articles (card game), and I need to automate this formatting constantly:

Find all "♣" and color the text green (#00b700). Find all "♦" and color the text orange (#ff8100). Find all "♥" and color the text red (#ff0000). Find all "♠" and color the text blue (#0000ff).

Answered: Mark and Michael helped build Google Apps Scripts to do this (see below). I modified the script and it's working perfectly.

Best Answer

To do a find-and-replace with formatting, you will need to use Google Apps Script. I am going to assume you are already familiar with GAS, but if not please reply with a comment on this post.

This script provides an example where you can change the background color of all 4 suits to the same color, by adding a menu to your document that will apply the formatting to all instances. Here is what the new menu will look like after adding the script to your Google Doc:

Utilities > Auto-Replace menu next to the "Help" menu in the Google Docs toolbar

And here is the code:

function onOpen() {
  DocumentApp.getUi()
      .createMenu('Utilities')
      .addItem('Auto-Replace', 'replaceSuits')
      .addToUi();
};

function replaceSuits() {
  var body = DocumentApp.getActiveDocument().getBody();      

  var found = body.findText("(♥|♦|♣|♠)");
  while (found) {
    var elem = found.getElement();
    if (found.isPartial()) {
      var start = found.getStartOffset();
      var end = found.getEndOffsetInclusive();
      elem.setBackgroundColor(start, end, "#ff0000");

    }
    else {
      elem.setBackgroundColor("#ff0000");
    }
    found = body.findText("(♥|♦|♣|♠)", found);
  }
};

This question is similar to Formatting in replaceText(), from which I borrowed code.

Here is a longer example which highlights each suit differently as described in your question (uses 4 separate code blocks for each suit, could definitely be refactored to allow shared code but this was the easiest way for me to code it): https://pastebin.com/7Y1L6BqF