Google Sheets: Extract Last Characters from String

Return the last number of characters of a string

function LAST_VALS(str,num){

 if(num >= str.length){

   return str;

 }

 return str.slice(str.length – num);

}


The provided code defines a function called LAST_VALS that takes two parameters: str and num. The function returns the last num characters from the str string. Here is a detailed explanation of how the function works:

  1. The function begins with an if statement: if(num >= str.length). This condition checks if the value of num is greater than or equal to the length of the str string. If this condition is true, it means that the function should return the entire str string because there are not enough characters to extract the last num characters. In this case, the function returns the str string as it is.
  2. If the condition in the if statement is false, the function proceeds to the next line: return str.slice(str.length – num);. The slice() method is used to extract a portion of the str string.
  3. The argument passed to slice() is str.length – num. This calculates the starting index from which the last num characters should be extracted. By subtracting num from str.length, we get the starting index of the desired portion.
  4. When slice() is called with a single argument, it extracts characters starting from the specified index until the end of the string. Therefore, str.slice(str.length – num) returns the last num characters from the str string.
  5. Finally, the extracted portion of the string is returned by the function.

In summary, the LAST_VALS function extracts the last num characters from the str string and returns them. If the value of num is greater than or equal to the length of the string, the entire str string is returned.

strnOutput
hello3llo
world2ld
foo bar2ar
test2st