Merging cells and removing placeholders in Google Docs tables using Apps Script

I’m working on a Google Docs project where I need to populate tables with data from a spreadsheet. The fourth column is used for images, but not every row contains one. After inserting all the data, I sometimes see leftover placeholders like {{Threshold gap photo}}.

I’m trying to remove these placeholders and merge the fourth column with the third if no image is present. I have a script that merges the columns, but it only works if the fourth column is empty from the start.

Here’s an updated version of my code:

function processDocument() {
  const doc = DocumentApp.openById('your-doc-id');
  const body = doc.getBody();
  const tables = body.getTables();

  tables.forEach(table => {
    const rows = table.getNumRows();
    for (let r = 0; r < rows; r++) {
      const cell4 = table.getCell(r, 3);
      if (cell4.getText().trim() === '{{Placeholder}}') {
        cell4.clear();
        mergeCells(table, r, 2, 3);
      }
    }
  });
}

function mergeCells(table, row, startCol, endCol) {
  // Implement cell merging logic here
}

Any ideas on how to adjust this so the placeholder text is properly removed before merging?

I’ve grappled with similar challenges in Google Docs tables. Here’s what worked for me:

First, consider using a more flexible approach to identify placeholders. Instead of an exact match, try something like:

if (cell4.getText().trim().startsWith(‘{{’) && cell4.getText().trim().endsWith(‘}}’)) {
cell4.setText(‘’);
mergeCells(table, r, 2, 3);
}

This catches any placeholder variations. Also, ensure your mergeCells function is working correctly. You might need to use table.getCell(r, 2).merge(table.getCell(r, 3)) for the actual merging.

Lastly, don’t forget to save your changes with doc.saveAndClose() at the end of your script. This step is crucial for the modifications to take effect.

Hope this helps you tackle the issue!

I’ve encountered similar issues when working with Google Docs tables and Apps Script. Here’s a suggestion that might help:

Instead of checking if the cell is exactly ‘{{Placeholder}}’, use a regular expression to match any placeholder-like text. This way, you’ll catch variations like ‘{{Threshold gap photo}}’.

Try modifying your code like this:

const placeholderRegex = /{{.*?}}/;
if (placeholderRegex.test(cell4.getText().trim())) {
  cell4.clear();
  mergeCells(table, r, 2, 3);
}

This should catch and remove any placeholder text enclosed in double curly braces before merging. Remember to implement the mergeCells function to handle the actual merging logic. Hope this helps!

hey, i’ve dealt with this before. try using cell4.setText('') instead of cell4.clear(). sometimes clear() doesn’t work right with placeholders. also, make sure ur mergeCells function is actually merging the cells properly. if it still doesnt work, maybe try looping thru the cells backwards? just a thought