Description
The JavaScript method charAt()
returns the character at a specified index in a string.
The below table summarizes its usage.
Usage Details | |
Syntax | str.charAt(index)
|
Parameters | index
|
Result | Returns a string representing the character at the specified index of an array. |
Category | String Methods |
Example 1: Using the method with an integer index value
For a valid integer index value, the method returns the character from the specified index.
var str = "Hello World!";
// Finding the character at index 6
document.write("Character at index 6 is : " + str.charAt(6));
Output:
Character at index 6 is : W
Example 2: Using the method with a non-integer index value
For a non-integer (or floating-point) index value, the method returns the character from the index determined by ignoring the decimal digits.
var str = "Hello World!";
// Finding character at index 6.3
document.write("Character at index 6.3 is : " + str.charAt(6.3));
// Finding character at index 6.9
document.write("Character at index 6.3 is : " + str.charAt(6.9));
// Finding character at index 6
document.write("Character at index 6.3 is : " + str.charAt(6));
Output:
Character at index 6.3 is : W
Character at index 6.9 is : W
Character at index 6 is : W
Example 3: Using the method without passing index value
When the index value is not passed, the method returns the character from the default index (which is 0) of the string.
var str = "Hello World!";
// Finding the character at default index, without passing index value.
document.write("Character at default index is : " + str.charAt());
// Finding the character at index 0
document.write("Character at index 0 is : " + str.charAt(0));
Output:
Character at default index is : H
Character at index 0 is : H
Example 4: Using the method with an index value out of range
When the index value is out of range, the method returns an empty string.
var str = "Hello World!";
// Finding the character at index 100
document.write("Character at index 100 is : " + str.charAt(100));
// Finding the character at index -10
document.write("Character at index -10 is : " + str.charAt(-10));
Output:
Character at index 100 is :
Character at index -10 is :
Overall
The JavaScript method charAt()
returns the character at a specified index in a string.