The search()
method in Apps Script is used to search for a specified substring within a string and return the index of the first occurrence of the substring. The method returns -1 if the substring is not found.
Example 1: Search for a Substring in a String
Suppose we have a string country
containing the name of a country, and we want to check if the string contains the substring “an”. We can use the search()
method like so:
var country = "Canada";
var index = country.search("an");
Logger.log(index);
In this example, we define a string country
containing the name of a country, and use the search()
method to check if the string contains the substring “an”. The resulting index of the first occurrence of the substring (“1”) is logged to the console.
Example 2: Search for a Substring with a Regular Expression
Suppose we have a string city
containing the name of a city, and we want to check if the string contains any non-alphabetic characters. We can use a regular expression and the search()
method like so:
var city = "New York 1";
var index = city.search(/[^A-Za-z\s]/);
Logger.log(index);
In this example, we define a string city
containing the name of a city, and use a regular expression /[^A-Za-z\s]/
to match any non-alphabetic characters. We then use the search()
method to find the index of the first occurrence of the matched substring. The resulting index (“8”) is logged to the console.
By using the search()
method in Apps Script, we can easily search for a substring within a string and get the index of the first occurrence. We can also use regular expressions to search for more complex patterns within the string.