The charCodeAt()
method in Apps Script is used to return the Unicode value of the character at a specified index in a string. The method returns a number representing the Unicode value of the character.
Example 1: Get the Unicode Value of a Character
Suppose we have a string country
containing the name of a country, and we want to get the Unicode value of the first character in the string. We can use the charCodeAt()
method like so:
var country = "Germany";
var unicodeValue = country.charCodeAt(0);
Logger.log(unicodeValue);
In this example, we define a string country
containing the name of a country, and use the charCodeAt()
method to get the Unicode value of the first character in the string. The resulting value (71) is logged to the console.
Example 2: Iterate Through a String and Get the Unicode Values of Each Character
Suppose we have a string city
containing the name of a city, and we want to iterate through the string and get the Unicode value of each character. We can use the charCodeAt()
method in a loop like so:
var city = "Paris";
var unicodeValues = [];
for (var i = 0; i < city.length; i++) {
unicodeValues.push(city.charCodeAt(i));
}
Logger.log(unicodeValues);
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 charCodeAt()
method to get the Unicode value of each character. The resulting array of values [80, 97, 114, 105, 115] is logged to the console.
By using the charCodeAt()
method in Apps Script, we can easily get the Unicode value of a character in a string, or iterate through a string and get the Unicode values of each character.