Reputation: 236
I would like to perform Split function for a specific range. Example, If i have a string like "HYT008", I need to have only 008 as result, means I would like to split last 3 letters from a string.
In Google Sheet I will perform this condition as =RIGHT(A2:A,3)
In Google Apps Script, I need to perform the action.
Upvotes: 1
Views: 4275
Reputation: 27390
There are multiple ways you can do that in JavaScript.
One way is to use the slice method and get the last 3 elements of your string: string.slice(-3)
.
then you can use map to apply this operation to the full column of your choice:
sh.getRange('A2:A'+sh.getLastRow()).getValues().flat().map(v=>[v.slice(-3)]);
The following script will get the values in column A, get the last 3 elements and paste them in column B:
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1'); // adjust this to the name of your sheet
const values = sh.getRange('A2:A'+sh.getLastRow()).getValues().flat().map(v=>[v.slice(-3)]);
sh.getRange(2,2,values.length,1).setValues(values); // paste them in column B
}
Sheet used for the code snippet:
Here you don't need to define the last element of your column.
=arrayformula(if(len(A2:A),right(A2:A,3),""))
Result:
Upvotes: 2