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

Veröffentlicht am: 07 Dezember 2022
auf dem Kanal: 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


Auf dieser Seite können Sie das Online-Video JavaScript tips — Using string.at(-1) to get the last character in a string mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Code 2020 07 Dezember 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 960 Mal angesehen und es wurde von 23 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!