The charAt()
method in JavaScript is used to return the character at a specified index in a string. This method takes a single argument, which is the index of the character to return. If the index is out of range, the charAt()
method returns an empty string.
Here is an example of how the charAt()
method works:
const string1 = 'Hello, world!';
const result = string1.charAt(7);
// the result will be: 'w'
In the code example above, we first declare a string called string1
that contains the text Hello, world!
. We then use the charAt()
method to get the character at index 7
in the string. The charAt()
method takes a single argument, which is the index of the character to return. In this case, we pass in the number 7
as the argument.
As a result of calling the charAt()
method, the result
variable will be set to 'w'
, which is the character at index 7
in the string1
string. If the index we were searching for was out of range (i.e., if we passed in a number greater than the length of the string), the result
variable would be set to an empty string.
Leave a Reply