How to replace text with an image in a Google Docs table?

I’m having trouble swapping out text for an image in a Google Docs table. My goal is to replace ‘%IMAGE%’ with a chart.

Here’s what I’ve tried:

let myTable = doc.getTables()[3];

for (let r = 0; r < myTable.getNumRows(); r++) {
  let currentRow = myTable.getRow(r);
  for (let c = 0; c < currentRow.getNumCells(); c++) {
    let cellContent = currentRow.getCell(c).getText();
    if (cellContent === '%IMAGE%') {
      currentRow.getCell(c).clear();
      currentRow.getCell(c).insertImage(0, myChart);
    }
  }
}

The script runs without errors, but it’s not replacing the text. What am I doing wrong? Any tips would be great!

I’ve dealt with similar challenges in Google Docs tables. One thing that’s often overlooked is the potential for hidden formatting or invisible characters. Try using a regular expression to match ‘%IMAGE%’ more flexibly:

let regex = /\s*%IMAGE%\s*/;
let myTable = doc.getTables()[3];

for (let r = 0; r < myTable.getNumRows(); r++) {
  for (let c = 0; c < myTable.getRow(r).getNumCells(); c++) {
    let cell = myTable.getCell(r, c);
    let text = cell.getText().trim();
    if (regex.test(text)) {
      cell.clear();
      cell.insertImage(0, myChart);
    }
  }
}

This approach should be more forgiving of extra spaces or invisible characters. Also, double-check that your myChart object is valid and the correct table is being accessed. If issues persist, consider using Logger.log() to output cell contents for debugging.

hey there! have u tried using .getBody() instead of .getTables()? sometimes the table structure can be tricky. also, make sure ur chart variable (myChart) is properly defined before inserting. if that doesn’t work, maybe try debugging with console.log() to see whats happening in each step. good luck!

I encountered a similar issue recently. The problem might be that getText() doesn’t always accurately represent cell content, especially with formatting. Try using getRangeElements() instead. Here’s a modified version that worked for me:

let myTable = doc.getTables()[3];
for (let r = 0; r < myTable.getNumRows(); r++) {
  let currentRow = myTable.getRow(r);
  for (let c = 0; c < currentRow.getNumCells(); c++) {
    let cell = currentRow.getCell(c);
    let elements = cell.getRange().getRangeElements();
    for (let e of elements) {
      if (e.getElement().asText().getText().trim() === '%IMAGE%') {
        cell.clear();
        cell.insertImage(0, myChart);
        break;
      }
    }
  }
}

This approach should handle the text replacement more reliably. Make sure your myChart variable is correctly defined before running the script.