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.

Loading TypeScript...

The at function returns a new string containing the code point at the given index.

Loading TypeScript...

The argument can be a positive or negative integer - if negative, the index counts backward from the last character.

Loading TypeScript...

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.

Loading TypeScript...

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.

Loading TypeScript...

To get the full Unicode code point at a given index, use codePointAt and fromCodePoint.

Loading TypeScript...

Retrieving character subsequences

You can retrieve a subsequence of the string's character with slice, which does support negative indexes.

Loading TypeScript...

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.

Loading TypeScript...

Was this page helpful?