In this article, I am going to show you some ways to get the last character of a string. There is a way that you do not need to care about the length of the string.

Contents

Method #1: string.charAt(index)

The String.prototype.charAt() method returns a string representing the character at the specified index.

The last character index is string.length - 1, you have the code:

const string = 'Hello World';
string.charAt(string.length - 1); // 'd'

If the input string is empty, this method returns an empty string.

const string = '';
string.charAt(string.length - 1); // ''

Method #2: string.slice(startIndex, endIndex)

The String.prototype.slice() method returns the part of the string between the start (inclusive) and the end (exclusive) indexes or the end of the string if the end index is omitted.

const string = 'Hello World';
string.slice(string.length - 1); // 'd'

Note that if the end index is omitted and the start index is a negative number, let’s say -N, this method returns the last N characters of the string. In this case, -N acts like string.length - N.

To get the last character, you just need to specify -1 as the start index:

const string = 'Hello World';
string.slice(-1); // 'd'

Yeah, this lets you do not need to know the string’s length.

Method #3: string.substring(startIndex, endIndex)

Similar to the String.prototype.slice() method, you can use the String.prototype.substring() method instead. But note that this method does not support the special negative index.

const string = 'Hello World';
string.substring(string.length - 1); // 'd'

Method #4: string.substr(startIndex, length) [DEPRECATED]

The String.prototype.substr() method returns the part of the string starting at the start index with the specified length. This method is deprecated so you should avoid using it.

Method #5: string[index] {DANGEROUS}

Similar to the String.prototype.charAt() method, the bracket notation is used for character access.

const string = 'Hello World';
string[string.length - 1]; // 'd'

I recommend not using this method. Since the bracket notation is available for arrays too, you do not know if the target object is a string or an array.

Conclusion

There are many ways to get the first character of a string, but in my opinion, the Method #2 that using the slice(-1) method is the best because of its convenience.