How to get the Last Character of a String in JavaScript

Strings in JavaScript essentially function as arrays of characters.
When you're working with strings, you might want to be able to get the last character of it.
In this post, we'll learn the different ways you can get the last character of a string in JavaScript.
Using the charAt() Method
An easy way to get the last character is to use the charAt()
method.
This method accepts an index and will return the character at that index.
All we need to do is pass in the index of the last character we want to get.
const string = "Hello World";
const lastCharacterIndex = string.length - 1;
const lastCharacter = string.charAt(lastCharacterIndex);
console.log(lastCharacter);
d
More concisely, we can also do this:
const string = "Hello World";
const lastCharacter = string.charAt(string.length - 1);
console.log(lastCharacter);
d
Using the slice() Method
We can also use the slice()
method to get the last character of a string.
Since slice takes a string and returns a substring, we can pass in the string and start the slicing at -1
, which will return the last character of the string.
const string = "Hello World";
const lastCharacter = string.slice(-1);
console.log(lastCharacter);
d
This works because when you provide slice
a negative number, it will start at the end of the string and work its way backwards.
Using the bracket notation
The final way you can get the last character of a string is to use the bracket notation.
Remember, because a string can be thought of as an array of characters, we can use the bracket notation to get the last character of a string by passing in the index of the last character.
const string = "Hello World";
const lastCharacter = string[string.length - 1];
console.log(lastCharacter);
d
Conclusion
In this post, we looked at the three different ways you can get the last character of a string in JavaScript.
Simply put, you can either use the charAt()
method, the slice()
method, or the bracket notation on a string to get the last character of it.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!