The charAt()
method returns the character at the specified index in a string.
Example
// string declaration
const string = "Hello World!";
// finding character at index 1
let index1 = string.charAt(1);
console.log("Character at index 1 is " + index1);
// Output:
// Character at index 1 is e
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
// string declaration
const string1 = "Hello World!";
// finding character at index 8
let index8 = string1.charAt(8);
console.log("Character at index 8 is " + index8);
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()
const string = "Hello World";
// finding character at index 6.3
let result1 = string.charAt(6.3);
console.log("Character at index 6.3 is " + result1);
// finding character at index 6.9
let result2 = string.charAt(6.9);
console.log("Character at index 6.9 is " + result2);
// finding character at index 6
let result3 = string.charAt(6);
console.log("Character at index 6 is " + result3);
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()
let sentence = "Happy Birthday to you!";
// passing empty parameter in charAt()
let index4 = sentence.charAt();
console.log("Character at index 0 is " + index4);
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()
let sentence = "Happy Birthday to you!";
// finding character at index 100
let result = sentence.charAt(100);
console.log("Character at index 100 is: " + result);
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()