The indexOf()
method in Apps Script is used to find the index of the first 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 First Occurrence
Suppose we have a string containing a list of cities separated by commas, like so: “New York, London, Paris, Tokyo”. We want to find the index of the first occurrence of the city “London” in the string. We can use the indexOf()
method like so:
var str = "New York, London, Paris, Tokyo";
var index = str.indexOf("London");
Logger.log(index);
In this example, we define a string str
containing the list of cities. We use the indexOf()
method on str
, passing “London” as the argument, to find the index of the first occurrence of “London” in the string. The method returns a value of 9
, indicating that the first occurrence of “London” starts at index 9 in the string.
Example 2: Finding the Index of the First Occurrence with a Starting Index
Suppose we have a country name, “United States of America”, and we want to find the index of the first occurrence of the letter “a” in the name, starting from the 10th index. We can use the indexOf()
method like so:
var str = "United States of America";
var index = str.indexOf("a", 10);
Logger.log(index);
In this example, we define a string str
containing the country name. We use the indexOf()
method on str
, passing “a” as the first argument and 10
as the second argument, to find the index of the first occurrence of “a” in the string starting from the 10th index. The method returns a value of 15
, indicating that the first occurrence of “a” after index 10 is at index 15 in the string.
By using the indexOf()
method in Apps Script, we can search for the first occurrence of a substring in a string, and use the index returned to perform various operations on the string.