.at()
In JavaScript, the .at()
method allows direct access to a character at a specified position in a string. Unlike the .charAt()
method, .at()
allows both positive and negative integers as an argument, simplifying the operation. Positive integers count indices from the start of the string, while negative integers count from the back. For example, -1
refers to the last character, -2
to the second last, and so on.
Syntax
string.at(index);
string
: The string from which the character is to be accessed.index
: An integer representing the position of the character to be accessed.
Example
Below is an example showcasing the functionality of the .at()
method:
const word = 'Codecademy is fun!';// Accessing the first character in the stringconsole.log(word.at(0));// Accessing the last character using a negative indexconsole.log(word.at(-1));// Accessing a character at a position that's beyond the string lengthconsole.log(word.at(100));
The above code produces the following output:
C!undefined
Note: The
.at()
method returnsundefined
for out-of-bound indices, unlike.charAt()
, which returns an empty string.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.