The charAt() method returns the character at the specified index in a string.
Example
charAt() Syntax
The syntax of the charAt() method is:
str.charAt(index)
Here, str is a string.
charAt() Parameters
The charAt() method takes in :
- index - An integer between 0 and str.length - 1. If index cannot be converted to integer or is not provided, the default value 0 is used.
Note: The str.length returns the length of a given string.
charAt() Return Value
- Returns a string representing the character at the specified index.
Example 1: Using charAt() Method With Integer Index Value
Output
Character at index 8 is r
In the above program, string1.charAt(8) returns the character of the given string which is at index 8.
Since, the indexing of a string starts from 0, the index of "r" is 8. Therefore, index8 returns "r".
Example 2: A Non-integer Index Value in charAt()
Output
Character at index 6.3 is W Character at index 6.9 is W Character at index 6 is W
Here, the non-integer index values 6.3 and 6.9 are converted to the nearest integer index 6. So both string.charAt(6.3) and string.charAt(6.9) return "W" just like string.charAt(6).
Example 3: Without passing parameter in charAt()
Output
Character at index 0 is H
Here, we have not passed any parameter in the charAt() method. The default index value is 0 so sentence.charAt() returns character at index 0 which is "H".
Example 4: Index Value Out of Range in charAt()
Output
Character at index 100 is:
In the above program, we have passed 100 as an index value. Since there is no element in index value 100 in "Happy Birthday to you!", the charAt() method returns an empty string.
Recommended Reading: JavaScript String charCodeAt()