Get the Second to Last Character in String in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Get the Second to Last Character in String #

To get the second to last character in a string, use bracket notation to access the string at index string.length - 2, e.g. str[str.length - 2]. The last index in the string is str.length - 1, so the second to last is str.length - 2.

index.js
const str = 'world'; const secondToLast = str[str.length - 2]; console.log(secondToLast); // ๐Ÿ‘‰๏ธ "l"

We used bracket notation [] to access the string at the second to last index.

Indexes are zero-based in JavaScript, meaning the first character in a string has an index of 0, and the last - string.length - 1.

By subtracting 1 from the last index, we get the second to last character in the string.

Note that if the string contains only 1 character or is empty, we would get an undefined value back.

index.js
const str = ''; const secondToLast = str[str.length - 2]; console.log(secondToLast); // ๐Ÿ‘‰๏ธ undefined

To avoid this scenario, we can use the String.charAt() method.

To get the second to last character in a string, call the charAt() method, passing it string.length - 2 as a parameter. The charAt method takes an integer between 0 and string.length - 1 and returns the character at the provided index.

index.js
const str = 'world'; const secondToLast = str.charAt(str.length - 2); console.log(secondToLast); // ๐Ÿ‘‰๏ธ "l"

The only parameter the charAt() method takes is the index at which to access the string.

This is different than using bracket [] notation, because if we provide an index that doesn't exist in the string, the charAt method returns an empty string.

index.js
const str = ''; const secondToLast = str.charAt(str.length - 2); console.log(secondToLast); // ๐Ÿ‘‰๏ธ ""

This is more consistent especially when using TypeScript. In the scenario where the string contains a single character or is empty, we get an empty string back, instead of undefined.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee