TypeScript String charCodeAt() Method
The String.charCodeAt() method in TypeScript returns the Unicode value of the character at a specified index in a string. It takes an integer index as a parameter and returns the corresponding Unicode value as a number.
Syntax
string.charCodeAt(index);
Parameter: This method accepts a single parameter as mentioned above and described below.
- index This parameter is an integer between 0 and 1 less than the length of the string.
Return Value: This method returns a number indicating the Unicode value of the character at the given index.
The below example illustrates the String charCodeAt() method in TypeScriptJS:
Example 1: Getting the Unicode Value of a Character
In this example we use charCodeAt(1) to get the Unicode value of the character at index 1 in str, which is e with a value of 101.
let str: string = "Hello";
let unicodeValue: number = str.charCodeAt(1);
console.log(unicodeValue);
Output:
101
Example 2: Iterating Over Characters and Getting Their Unicode Values
In this example we iterates through str, logging each character's Unicode value using charCodeAt().
let str: string = "Java";
for (let i = 0; i < str.length; i++) {
console.log(`Character at ${i} is : ${str.charCodeAt(i)}`);
}
Output:
Character at 0 is : 74
Character at 1 is : 97
Character at 2 is : 118
Character at 3 is : 97
Notes:
- The charCodeAt() method returns NaN if the specified index is out of the string's range.
- Unicode values are numerical representations of characters.