DEV Community

Josua Schmid
Josua Schmid

Posted on

Auto-colorize Google Docs

Formatting options in Google Docs are limited. And that's good because formatting can be a lot of manual work (e.g. in Microsoft Word). But sometimes it would be nice to have some fine-grained auto-formatting feature like coloring a certain word if it occurs in the text.

Luckily there is Google Apps Script. You can apply some JavaScript code to your documents very easily, like for example to color some words selected with a Regular Expression:

function colorText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();

  for (var i = 0; i < paragraphs.length; i++) {
    var searchResult = paragraphs[i].findText('^.*\:');

    if (searchResult) {
      var startIndex = searchResult.getStartOffset();
      var endIndex = searchResult.getEndOffsetInclusive();

      searchResult.getElement().asText().setForegroundColor(
        startIndex, endIndex, '#571f4e'
      );
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)