In JavaScript, the “charAt()” method assists in performing such actions as extracting the first character. Moreover, this method is not limited to only fetching the starting character; it can be used to extract any character based on its position or index.
In this guide, we will demonstrate what is charAt() in JavaScript.
What is charAt() in JavaScript?
In JavaScript, the “charAt()” method can be utilized to return a character from a certain index. As in a string, characters are indexed from left to right, and the first character is always on the 0th index, and the last character is on the total string length – 1 index.
The below image illustrates how the characters are indexed in a string:
How to Use charAt() in JavaScript?
In order to use charAt() in JavaScript, follow the below-given syntax:
Here, the charAt() method will be invoked for the specified string, where the index represents the position of a character present in a string. The value of the index is 0 by default.
So, let’s understand how to use the charAt() method with the help of an example.
Example 1: Fetch Single Character Using charAt() Method
In our example, we will initialize a string as “str” and assign some text to it:
Then, declare a variable “print” and use the charAt() method with the string as “str.charAt(0)”; where 0 is the index of the string str:
Now, print the output using the console.log() method:
It can be seen that we have successfully fetched the first character of the given string using the charAt()” method
Want to return two characters from the same string using charAt() method? Let’s move ahead to the next example.
Example 2: Fetch Multiple Characters Using charAt() Method
To return the two characters from the same string, we will use the charAt() method twice and concatenate the resultant values with the help of the “+” operator. As in the second charAt() method, we will set the index as “5” to get the “sixth” character from our string along with the first character:
Output
We have described in detail what the charAt() method is and how it can be used.
Conclusion
In JavaScript, the “charAt()” method is used to return a character from a certain index. If no index is mentioned within the charAt() method, it will consider it as 0 and return the first character. To return the two characters from the same string, you can utilize the two charAt() and concatenate the values with the help of the + operator. In this manual, we have learned what is charAt() in JavaScript with examples.