Remove line breaks within cells in a range (\n) by Google Apps Script

4

2

In a Google Spreadsheet I would normally do the following:

  1. Go to Find and Replace
  2. Check "regular expressions"
  3. Find \n and replace with null

I have searched and for the life of me I'm unable to find a Googl Apps Script that I can use to do this process by code.

WtfgJFnaSmKqsRh yRzNhUgueEJw

Posted 2014-09-18T23:19:43.853

Reputation: 41

Question was closed 2015-06-30T11:56:58.730

Answers

2

var ui = SpreadsheetApp.getUi();

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Automation')
      .addItem('Delete Enters', 'deleteEnters')
      .addToUi();
}

function deleteEnters() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  if (!sheet){
    ui.alert("There is no sheet with config!"); 
  }

  var lastColumn = sheet.getLastColumn();
  var lastRow = sheet.getLastRow();

  for (i = 1; i <= lastColumn; i++) {
    for (j = 1; j <= lastRow; j++) {
      var tempText = sheet.getRange(j,i).getValue();
      tempText = tempText.replace(/\n/g,"");
      sheet.getRange(j, i).setValue(tempText);
    }
  }  
}

Hi, I made for you this simple code. Thanks to this, you can choose on current sheet option Automation > Delete Enters and script automatically replace \n for ""

You can change this line:

tempText = tempText.replace(/\n/g,"");

for your own regex, if you want replace enters per something else.

KIT

Posted 2014-09-18T23:19:43.853

Reputation: 21

1While this may answer the question, it would be a better answer if you could provide some explanation why it does so. – DavidPostill – 2015-06-27T10:25:32.960