How do I get Last Character of the String in Javascript

Last updated Jun 15, 2022

In this Javascript example we will cover how to get last character of a given string. We know that like other programming languages String is an array of characters in Javascript. So we apply array functions on string to get last character of the given string in Javascript.
We have differnt ways to do this

  • substr()
  • charAt()
  • slice()
  • split()

 

Javascript get last character of the String

 

Using substr() function:
This substr() function takes two parameters to get the last character of the given string. one is the index from where we need to take the substring and other one is the length of the substring. In this we will pass index -1 to get the last character.
 

var str = "Javascript";
console.log(str.substr(-1));

output:
 

t


We can also get the above output by using the string length feature to pass the index and length parameters.

var str = "Javascript";
console.log(str.substring(str.length-1, str.length));

output:
t

 


Using charAt() function:
This charAt() function will return the character of the given index value. To get the last character we need to pass string length-1, this will return the last character of the string.


 

var str = "Javascript";
console.log(str.charAt(str.length - 1));

 

output:
t


Using slice() function:
slice() is a general function to perform operations on the String. This will work as substr() function, but this substr is deprecated and will use slice() function.
 

var str = "Javascript";
console.log(str.slice(-1));

 

var str = "Javascript";
console.log(str.slice(str.length-1, str.length));


 

output:
t

 

 

Using split() function:
split() function will breaks the given string into parts based on passed delimiter, to get last character we first need to pass "" delimiter to the split function, then it breaks and return each character as an array. From the array get the last index value to get the last char character of the string.

var str = "Javascript";
console.log(str.split("")[str.length - 1]);

 

output:
t

 

Conclusion: In this Javascript example we covered how to get last character of the given string using differnt functions like substr,slice,split and charAt. These functions will work on all browsers.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

52 Views