1

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.

7
  • what is the perceived benefit of having a script do this over having a formula do it? Commented Dec 18, 2020 at 17:34
  • Here's the JavaScript string methods: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 18, 2020 at 17:35
  • My Sheet is getting stuck while i perform the Right formula, Commented Dec 18, 2020 at 17:35
  • 1
    I have 30k+ data need to split like this Commented Dec 18, 2020 at 17:35
  • Have you tried =arrayformula(right(a2:a30000,3)) Commented Dec 18, 2020 at 17:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Moses I added also an arrayformula in case you can use it, could be quite useful.
Complete answer with good explanation. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.