TypeScript String charAt()
Syntax & Examples
String.charAt() method
The `charAt()` method of a String object returns the character at a specified index. If the specified index is out of range, it returns an empty string.
Syntax of String.charAt()
The syntax of String.charAt() method is:
charAt(pos: number): string
This charAt() method of String returns the character located at the given index in a string. The index is zero-based, meaning the first character is at index 0, the second at index 1, and so on. If the specified index is less than 0 or greater than or equal to the string's length, an empty string is returned.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
pos | required | The zero-based index of the character to return. Must be an integer. |
Return Type
String.charAt() returns value of type string
.
✐ Examples
1 Using charAt() to retrieve a character
You can use the `charAt()` method to retrieve a character from a string at a specific index.
For example,
- Define a string variable
str
with some text. - Call the
charAt()
method on the string with the desired index. - Store the returned character in a variable or use it directly in your logic.
- Log the character to the console using the
console.log()
method.
TypeScript Program
const str = 'Hello, World!';
const char = str.charAt(7);
console.log(char);
Output
W
2 Using charAt() with an out-of-range index
If you call `charAt()` with an index that is out of the string's range, it will return an empty string.
For example,
- Define a string variable
str
with some text. - Call the
charAt()
method on the string with an out-of-range index. - Log the result to the console using the
console.log()
method.
TypeScript Program
const str = 'Hello';
const char = str.charAt(10);
console.log(char);
Output
3 Using charAt() in a loop
You can use the `charAt()` method in a loop to access each character in a string.
For example,
- Define a string variable
str
with some text. - Use a for loop to iterate through the string based on its length.
- Call the
charAt()
method with the current index to retrieve each character. - Log each character to the console using the
console.log()
method.
TypeScript Program
const str = 'Hello';
for (let i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
Output
H E L L O
Summary
In this TypeScript tutorial, we learned about charAt() method of String: the syntax and few working examples with output and detailed explanation for each example.