Moses
Moses

Reputation: 236

Google Script to Split Right String Values

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.

Here is the scenario - enter image description here

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

Answers (1)

Marios
Marios

Reputation: 27390

Explanation:

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)]);

Google Apps Script Solution:

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:

enter image description here


Google Sheets Formula Solution:

Here you don't need to define the last element of your column.

=arrayformula(if(len(A2:A),right(A2:A,3),""))

Result:

enter image description here

Upvotes: 2

Related Questions