In this article we will learn how to get last letter of string.
It is very common to get last letter of a string in JavaScript.
There is more than one way to solve this problem:
- Using
slice()
method - Using
charAt()
method - Using
at()
method - Using
subString()
method
Problem
Now we have a problem, which is that we want to get the last letter of the string.
Imagine we have a string like this:
"Hello World"
And we want to get the last letter.
"d"
How to solve this problem?
As we said before, we have more than one solution and in this tutorial we will explain all of them.
Get last letter using slice()
method
We can use slice
method to get the last letter of string in JavaScript.
Example
// String
const myString = "Hello World";
// Get letters from `0` to `1`
// (last letter)
const lastLetter = myString.slice(-1);
// Result:
console.log(lastLetter);
Output
d
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (Source: MDN)
Get last letter using charAt()
method
We can use charAt()
method to get last letter of string.
Example
// String
const myString = "Hello World";
// Get last letter
const lastLetter = myString.charAt(myString.length - 1);
// Result:
console.log(lastLetter);
Output
d
The String object's charAt()
method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. (Source: MDN)
Get last letter using at()
method
We can use at()
method to get last letter as well.
Example
// String
const myString = "Hello World";
// Get last letter
const lastLetter = myString.at(myString.length - 1);
// Result:
console.log(lastLetter);
Output
d
Get last letter using subString()
method
We can use subString
method to get last letter as well.
// String
const myString = "Hello World";
// Get last letter
const lastLetter = myString.substring(myString.length - 1);
// Result:
console.log(lastLetter);
Output
d
The substring()
method returns the part of the string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. (Source: MDN)
Thank you for reading
Thank you for reading my blog. 🚀