How to get the last character of a string?
An elegant and short alternative, is the String.prototype.slice
method.
Just by:
str.slice(-1);
A negative start index slices the string from length+index
, to length
, being index -1
, the last character is extracted:
"abc".slice(-1); // "c";
Use charAt
:
The charAt() method returns the character at the specified index in a string.
You can use this method in conjunction with the length
property of a string to get the last character in that string.
For example:
const myString = "linto.yahoo.com.";
const stringLength = myString.length; // this will be 16
console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string