JavaScript tips — Using string.at(-1) to get the last character in a string

Опубликовано: 07 Декабрь 2022
на канале: Code 2020
960
23

The string.at method lets you get characters in a string by index, much like using a bracket accessor. However string.at also accepts negative indexes. These count backwards from the end of the string.

To get the last character in a string, simply call myString.at(-1). Keep in mind that if the string does not contain enough characters, string.at will return undefined for both positive and negative indexes.

PS: Technically bracket accessors and string.at do not return characters but instead return strings created from code points at the given index. This is important to understand when working with emoji and multibyte characters.

#javascript