Google Sheets Apps Script -- select value from cell with multiple lines

Viewed 299

This is in GoogleSheets, using AppsScript.

Suppose I have a cell in A1 that contains the following value:

Dog Dog
Cat Cat Cat
Lion

I know I can select the entire contents of the cell using .getValue(), but how would I select just the fist line, Dog Dog, or just the second line, Cat Cat Cat? Each line may have multiple words associated to it, so I can't simply split by using the space.

2 Answers

Great question. You can still use .getValue() but you will need to add one more piece to break apart the value to the desired string. value.split("\n")[0]; will get the first linebreak listed. If you want to get a different line then change [0] to another number.

function selectSingleLine() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var tab = ss.getSheetByName('Sheet1');
  var value = tab.getRange(1,1).getValue();  
  var firstBreak = value.split("\n")[0]; 
  var secondBreak = value.split("\n")[1];
  
}

You can split by using char(10)

=split(A1,char(10))
Related