The charAt function in JavaScript is utilized to retrieve the character value located at a particular index within a given string.
The index in a string begins at 0 and continues up to n-1, with n representing the string's length. It's important to note that the index value cannot be negative or exceed the length of the string.
Syntax
The syntax for the charAt method is as follows:
Example
String.charAt(index)
Parameter
index - It represent the position of a character.
Returns
A char value
JavaScript String charAt Method Example
Let's see some examples of charAt method.
Example 1
Let's see a simple example to print a character.
Example
<script>
var str="Example";
document.writeln(str.charAt(4));
</script>
Output:
Example 2
In this example, we will not pass an index value.
Example
<script>
var str="Example";
document.writeln(str.charAt());//print first character
</script>
Output:
Example 3
In this instance, we will display the final character.
Example
<script>
var str="Example";
document.writeln(str.charAt(str.length-1));
</script>
Output: