The JavaScript string.at() method
The at() method returns the character at a given index, and crucially it accepts negative indices. str.at(-1) is the last character, cleaner than str[str.length - 1] or str.charAt(str.length - 1). For positive indices it works like bracket access.
Overview
at() reads a single character from a string by index, with the same headline feature as its array namesake array.at(): it understands negative indices. "hello".at(-1) is "o", "hello".at(-2) is "l": no more str.length - 1 arithmetic to grab characters from the end.
For non-negative indices that are in range it behaves just like bracket access (str[2]) and charAt(). The win is entirely at the end of the string: the last character, the file extension's last letter, the final digit. It returns undefined for an out-of-range index.
It's the modern, readable choice for end-relative character access. One Unicode note shared by all index-based string access: an emoji or astral character spans two UTF-16 units, so at() reads code units, not whole code points. For emoji-safe work, iterate with for...of or spread the string.
Syntax
str.at(index)
"hello".at(0) // "h"
"hello".at(-1) // "o" (last character)
"hello".at(-2) // "l"
Parameters
The string.at() method accepts the following parameters.
| Parameter | Description |
|---|---|
index |
The position to read. Negative values count back from the end (-1 is the last character). |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const word = 'JavaScript';
document.getElementById('out').textContent =
'first: ' + word.at(0) + '\n' +
'last: ' + word.at(-1) + '\n' +
'prev: ' + word.at(-2); // first: J / last: t / prev: p
</script>
Best practices
- Use
str.at(-1)for the last character instead ofstr[str.length - 1]. - For ordinary forward access, bracket notation
str[i]is fine. - It returns
undefinedfor out-of-range indices. - For emoji-safe iteration, use for...of or spread, since
at()reads code units.
Frequently asked questions
How do I get the last character of a string?
str.at(-1), which counts from the end (cleaner than str[str.length - 1]).What is the difference between at() and charAt()?
at() returns undefined where charAt() returns an empty string. at() also accepts negative indices to count from the end, which charAt() does not.What does string.at() return out of range?
undefined.