charAt() method

The charAt() method in Apps Script is used to return the character at a specified index in a string. The method returns a string containing the character at the specified index.

Example 1: Get a Character at a Specific Index
Suppose we have a string country containing the name of a country, and we want to get the character at the third index in the string. We can use the charAt() method like so:

var country = "Canada";
var char = country.charAt(2);
Logger.log(char);

In this example, we define a string country containing the name of a country, and use the charAt() method to get the character at the third index in the string. The resulting character (“n”) is logged to the console.

Example 2: Iterate Through a String and Get Each Character
Suppose we have a string city containing the name of a city, and we want to iterate through the string and get each character. We can use the charAt() method in a loop like so:

var city = "Rome";
var chars = "";
for (var i = 0; i < city.length; i++) {
  chars += city.charAt(i) + " ";
}
Logger.log(chars);

In this example, we define a string city containing the name of a city. We use a for loop to iterate over the string, and use the charAt() method to get each character. The resulting string of characters (“R o m e “) is logged to the console.

By using the charAt() method in Apps Script, we can easily get a specific character in a string or iterate through a string and get each character.