The includes()
method in Apps Script is used to determine whether a string includes a specified substring or not. It returns true
if the substring is found, and false
otherwise.
Example 1: Checking if a String Includes a Substring
Suppose we have a string containing the name of a country, like so: “United States of America”. We want to check if the string includes the word “States”. We can use the includes()
method like so:
var str = "United States of America";
var result = str.includes("States");
Logger.log(result);
In this example, we define a string str
containing the name of a country. We use the includes()
method on str
, passing “States” as the argument, to check if the string includes the word “States”. The method returns a value of true
, indicating that the word “States” is present in the string.
Example 2: Checking if a String Includes a Substring with a Starting Index
Suppose we have a string containing a list of cities separated by commas, like so: “New York, London, Paris, Tokyo”. We want to check if the string includes the city “Paris” starting from the index 15. We can use the includes()
method like so:
var str = "New York, London, Paris, Tokyo";
var result = str.includes("Paris", 15);
Logger.log(result);
In this example, we define a string str
containing a list of cities. We use the includes()
method on str
, passing “Paris” as the first argument and 15
as the second argument, to check if the string includes the city “Paris” starting from the index 15. The method returns a value of false
, indicating that the city “Paris” is not present in the string starting from index 15.
By using the includes()
method in Apps Script, we can easily check if a substring is present in a string or not, and use the result to perform various operations on the string.