0

I am new to Google Scripts and I want to replace the \n text in my cells with the newline character. I use this code:

   for (var row = 0; row < data.length; row++) {
    for (var col = 0; col < data[row].length; col++) {
      var sValue = data[row][col];       
      sValue = sValue.toString().replaceAll("\n", String.fromCharCode(10));

      //Set the new value:
      var cell = sheet.getRange(row+1, col+1); 
      cell.setValue(sValue );
    }     

But it does nothing. The text is not changed. Any help here?

Ton
  • 9,235
  • 15
  • 59
  • 103
  • 1
    should be `"\\n"` – TheMaster Apr 16 '20 at 13:37
  • The approach is going to take a long time to execute as it has to write to the sheet many times. Better approach will be to do the replacement in the array and write the entire array back to the sheet – arul selvan Apr 16 '20 at 13:57
  • [https://stackoverflow.com/questions/26480857/how-do-i-replace-text-in-a-spreadsheet-with-google-apps-script](https://stackoverflow.com/questions/26480857/how-do-i-replace-text-in-a-spreadsheet-with-google-apps-script) – arul selvan Apr 16 '20 at 14:33
  • Sorry, the problem was in the replaceAll() function. It was not working properly. I copied it from somewhere. If I use the function replace() it works, but it only replaces the first \n – Ton Apr 16 '20 at 15:29
  • 1
    Try this regular expression /\\n/g – Cooper Apr 16 '20 at 15:55
  • It works! Thanks. Will you create an answer so I can mark it as the correct answer? – Ton Apr 16 '20 at 15:59

0 Answers0