In this tutorial let’s learn about How to Get the Last Character of a String in JavaScript. The task is to get the last character of a string given a length of len
. There are numerous approaches to solving this issue, some of which are discussed below:
Contents
Get the Last Character of a String using charAt() in JavaScript
To get the last character of a string, use the string’s charAt() method, providing it the last index as an argument. The character at the specified position in a string is returned by the charAt() function. It uses the target character’s position as a parameter. As a result, to get the last character of the string, we can send length – 1 (since the string index starts at 0) as an argument to it.
For example, str.charAt(str.length – 1) returns a new string with the string’s last character.
Code Example :
const str = 'Similar Geeks';
const last = str.charAt(str.length - 1);
console.log(last); // print s
Output :
s
Get the Last Character of a String using str.slice() in JavaScript
The slice() function is another popular way to operate with strings. It accepts two parameters: the start and end indexes. They behave differently because slice(-1) returns the last character of the string. The string.slice() function is used to return a part of the given input string
Syntax for str.slice()
str.slice(starting_index, ending_index)
Code Example :
const str = 'Similar Geeks';
const last = str.slice(-1);
console.log(last); // print s
Output :
s
Using split() to Get the Last Character of a String in JavaScript
We can divide a string into substrings using the split() function. The function separates the string based on the delimiter we supply it as an argument. We can use “” (empty character) as a delimiter and obtain all the characters individually in an array to get the last character of the string. The last element of the array must then be obtained.
Code Example :
const str = 'Similar Geeks';
const last = str.split("")[str.length - 1];
console.log(last); // print s
Output :
s
Get the Last Character of a String using Index in JavaScript
We can also get the last character of a string with javascript using the standard techniques. Because javascript treats a string object as an array of characters, we may use the string[length – 1] syntax to get the last entry of that array.
Code Example :
const str = 'Similar Geeks';
const last = str[str.length - 1];
console.log(last); // print s
Output :
s
To get the last character of a string, use square bracket notation to access the string at the last index. In the above example, str[str.length – 1] returns the string’s final character.
Conclusion
In this article we learnt different ways to Get the Last Character of a String in JavaScript. charAt(), substr() and slice() are preferred and one of the easy ways.
Similar Posts:
How to Convert String to Float in Python
How to Convert Bytes to String in Python