2

I'm having an issue where when I insert an image into a cell in Google Docs, it also adds a newline which I can't seem to get rid of... I've tried what was suggested here but that doesn't work for some reason. This is my code:

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.clear();
  var table = body.appendTable();
  var tr = table.appendTableRow()
  tr.appendTableCell();
  tr.appendTableCell();
  var resp01 = UrlFetchApp.fetch("http://www.cincinnati-oh.gov/cityofcincinnati/assets/Image/Logos/cityofcincinnati.png");

  var cell = table.getRow(0).getCell(0);
  cell.insertImage(0,resp01.getBlob());
    table.getCell(0,0).editAsText().replaceText("\\v+", "");
}

Thanks in advance!

Community
  • 1
  • 1
  • 2
    I'm not sure why Apps Script does not recognise `\n` or `\r` in regex searches :/ A quick and dirty solution for your use case is to remove the text of the cell like this: `table.getCell(0,0).setText("");` hopefully someone come with a better solution (: – ocordova Sep 15 '16 at 13:39
  • Did you try constructing the regex with `new RegExp()`? It tends to create much fewer problems – Robin Gertenbach Sep 15 '16 at 22:11
  • @RobinGertenbach could you please show me via a code example of how to use that. – Thibault Molleman Sep 16 '16 at 06:22
  • 1
    See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) for construction and examples. – Robin Gertenbach Sep 16 '16 at 06:55
  • @RobinGertenbach The method [replaceText](https://developers.google.com/apps-script/reference/document/text#replacetextsearchpattern-replacement) is not a JavaScript method, and does not accept JavaScript's regex objects. –  Dec 28 '16 at 04:22

1 Answers1

0

I wasn't able to get rid of the character (with charcode 10, by the way - not 13) using replaceText. The nuclear option is to drop to the level of plain strings and use the JavaScript replace method:

cell.setText(cell.getText().replace(/\n+$/, ""));

This removes the new line. As I said, this is the nuclear option: any formatting (bold, italic) that the cell had would be lost.

If the cell is not expected to have any text besides the image, the shorter cell.setText(""); has the same effect.