String.prototype.at
Returns the character at a position; negative indexes are allowed.
Available since: ES2022
Syntax
str.at(index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | number | The position of the character, counting from zero. A negative number counts from the end of the string. |
Return value
string | undefinedA one-character string, or undefined if there is no such position.
Examples
The first and the last character:
console.log('Hello'.at(0));
console.log('Hello'.at(-1));Output:
H
oA position outside the string:
console.log('Hi'.at(5));Output:
undefinedNotes
The main difference from str[i] is negative indexes: str.at(-1) instead of str[str.length - 1].
See also
- String.prototype.charAt — Returns the character at a position.
- String.prototype.slice — Returns part of a string.
- Array.prototype.at — Returns the element at an index; negative indexes are allowed.
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.