Search code examples
javascriptstring

How to select last two characters of a string


I need to select last two characters from the variable, whether it is digit or letters.

For example:

var member = "my name is Mate";

I would like to show last two letters from the string in the member variable.


Solution

  • You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

    var member = "my name is Mate";
    
    var last2 = member.slice(-2);
    
    alert(last2); // "te"