TypeScript String charAt() Method
Last Updated :
19 Jul, 2024
Improve
The String.prototype.charAt() method in TypeScript is used to return the character at the specified index of a string. The characters in the string are indexed from left to right, starting at 0.
Syntax:
string.charAt( index )
Parameter: This method accepts a single parameter as mentioned above and described below:
- index: It is an integer value between 0 and 1 less than the length of the string.
Return Value: This method returns a character for the given index in the argument.
Below examples illustrate the working of charAt() method in TypeScript:
Examples of TypeScript String charAt() Method
Example 1: Basic Usage of charAt()
In this example, we will use the charAt() method to get the character at a specific index in a string.
const str: string = "Hello, World!";
const charAtIndex: string = str.charAt(4);
console.log(charAtIndex);
Output:
o
Example 2: Iterating Over a String Using charAt()
In this example, we will demonstrate how to use charAt() in a loop to access and print each character of a string.
const str: string = "JavaScript";
for (let i = 0; i < str.length; i++) {
console.log(`str.charAt(${i}) is: ${str.charAt(i)}`);
}
Output:
str.charAt(0) is:J
str.charAt(1) is:a