lastIndexOf() method

The lastIndexOf() method in Apps Script is used to find the index of the last occurrence of a specified substring in a string. It takes one or two arguments: the first argument is the substring to search for, and the second argument is the starting index for the search (optional).

Example 1: Finding the Index of the Last Occurrence
Suppose we have a string containing a list of cities separated by commas, like so: “New York, London, Paris, Tokyo, London”. We want to find the index of the last occurrence of the city “London” in the string. We can use the lastIndexOf() method like so:

var str = "New York, London, Paris, Tokyo, London";
var index = str.lastIndexOf("London");
Logger.log(index);

In this example, we define a string str containing the list of cities. We use the lastIndexOf() method on str, passing “London” as the argument, to find the index of the last occurrence of “London” in the string. The method returns a value of 22, indicating that the last occurrence of “London” starts at index 22 in the string.

Example 2: Finding the Index of the Last Occurrence with a Starting Index
Suppose we have a country name, “United States of America”, and we want to find the index of the last occurrence of the letter “a” in the name, starting from the 10th index. We can use the lastIndexOf() method like so:

var str = "United States of America";
var index = str.lastIndexOf("a", 10);
Logger.log(index);

In this example, we define a string str containing the country name. We use the lastIndexOf() method on str, passing “a” as the first argument and 10 as the second argument, to find the index of the last occurrence of “a” in the string starting from the 10th index. The method returns a value of 9, indicating that the last occurrence of “a” before index 10 is at index 9 in the string.

By using the lastIndexOf() method in Apps Script, we can search for the last occurrence of a substring in a string, and use the index returned to perform various operations on the string.