how to get the last character of a string?
How to get the last character of the string:
The last character of this string is “.”
How can I find this?
An elegant and short alternative, is the
A negative start index slices the string from
length, being index
-1, the last character is extracted:
"abc".slice(-1); // "c";
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.
var myString = "linto.yahoo.com."; var stringLength = myString.length; // this will be 16 var lastChar = myString.charAt(stringLength - 1); // this will be the string "."
str.charAt(str.length - 1)
Some browsers allow (as a non-standard extension) you to shorten this to:
str[str.length - 1];
You can achieve this using different ways but with different performance,
1. Using bracket notation:
var str = "Test";
var lastLetter = str[str.length - 1];
But it’s not recommended to use brackets. Check the reasons here
var lastLetter = str.charAt(str.length - 1)
This is readable and fastest among others. It is most recommended way.
str.substring(str.length - 1);
It’s slightly faster than substring.
You can check the performance here
You can use
But it is not supported in IE. Check more details about endsWith here
Use substr with parameter -1:
To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).
An easy way of doing it is using this 🙂
var word = "waffle" word.endsWith("e")