Search code examples
google-apps-scriptgoogle-docs

Select and format text in table cells based on Regex criteria


How do I loop through all the cells in a table, selecting text in each cell based on Regex criteria, and format those cells?

EDIT: I can set row attributes using table.getRow(n).getCell(n) but how do I format specific text in each cell?

I need to make the name appearing at the start of each cell bold:

enter image description here

Here's the sample doc.


Solution

  • I believe your goal is as follows.

    • In your sample situation, you want to convert the value of Monserrat Banks of Monserrat Banks: Fringilla dolor ultricies aliquam dolor. to the bold type in a table on Google Document.
    • You want to achieve this using Google Apps Script.

    In this case, how about the following sample script?

    Sample script:

    Please copy and paste the following script to the script editor of Google Document and run the script.

    function myFunction() {
      const table = DocumentApp.getActiveDocument().getBody().getTables()[0];
      const rows = table.getNumRows();
      for (let r = 0; r < rows; r++) {
        const row = table.getRow(r);
        const cols = row.getNumCells();
        for (let c = 0; c < cols; c++) {
          const cell = row.getCell(c);
          const f = cell.findText(".*:");
          if (!f) continue;
          cell.editAsText().setBold(f.getStartOffset(), f.getEndOffsetInclusive() - 1, true);
        }
      }
    }
    
    • From your provided Document, in this sample, the 1st table is used. When you want to use another table, please modify the above script.

    Testing:

    When this script is run to your provided Google Document, the following result is obtained.

    From:

    enter image description here

    To:

    enter image description here

    Rererences: