Retrieving characters
You can retrieve individual characters from a string by index (character position) in the same way you would retrieve elements from an array.
When you retrieve the character at index 0, you are actually retrieving a single UTF-16 code unit at the specified offset.
Accessing an out-of-bound array index like emoji[2]
or even emoji[-1]
produces undefined
, and does not throw an error.
The at
function returns a new string containing the code point at the given index.
The argument can be a positive or negative integer - if negative, the index counts backward from the last character.
The at
function requires your TypeScript compiler target to be set to ES2022
or higher. If you are targeting older JavaScript versions or simply don't need negative indexing, the charAt
function is an equivalent option for retrieving individual characters.
The at
and charAt
functions always return a new string with the single UTF-16 code point at the given index, so it may return lone surrogates.
To get the full Unicode code point at a given index, use codePointAt
and fromCodePoint
.
Retrieving character subsequences
You can retrieve a subsequence of the string's character with slice
, which does support negative indexes.
While at
is the most concise way to retrieve a single character of a string, the same string can also be retrieved with slice
and charAt
.