Search code examples
google-apps-scriptformattinggoogle-docs

How to write a Google Apps Script function to find and format a specific character throughout a doc?


I'm using docs to save ASCII drawings for a project, and to make it more readable I need the % character to always be gray. However, manually formatting each % would take forever. I suspect I'll need to use a regular expression to locate all of the %, but as an amateur programmer I'm not sure how to write the actual function.

In short, the function needs to:

  1. Find all % characters.
  2. Change text color to gray (#cccccc).

The function only needs to be executed once (not constantly in the background).

Thank you for your help!

I've checked the documentation here: https://developers.google.com/apps-script/guides/docs, but I wasn't able to figure out how to find and format specific text.


Solution

  • I've created a simple example of how to color the %. This runs from a new menu item and can be run any time.

    function onOpen() {
      let ui = DocumentApp.getUi();
      let menu = ui.createMenu("My Menu");
      menu.addItem("Change %","changeColor");
      menu.addToUi();
    }
    
    function changeColor() {
      try {
        let doc = DocumentApp.getActiveDocument();
        let body = doc.getBody();
        let range = body.findText("%");
        while( range ) {
          let text = range.getElement().asText();
          if( range.isPartial() ) {
            let start = range.getStartOffset();
            let end = range.getEndOffsetInclusive();
            text.setForegroundColor(start,end,"#cccccc");
          }
          else {
            text.setForegroundColor("#cccccc");
          }
          range = body.findText("%",range);
        }
      }
      catch(err){
        console.log("Error in changeColor: "+err);
      }
    }
    

    References: