how to get the last character of a string?

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?


Solution 1:

An elegant and short alternative, is the String.prototype.slice method.

Just by:


A negative start index slices the string from length+index, to length, being index -1, the last character is extracted:

"abc".slice(-1); // "c";

Solution 2:

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:

var myString = "";
var stringLength = myString.length; // this will be 16
var lastChar = myString.charAt(stringLength - 1); // this will be the string "."

Solution 3:

str.charAt(str.length - 1)

Some browsers allow (as a non-standard extension) you to shorten this to:

str[str.length - 1];

Solution 4:

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

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:


It’s slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

Solution 5:

Use substr with parameter -1:


equals “.”


To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).

Solution 6:

An easy way of doing it is using this 🙂

var word = "waffle"