Home » Javascript » How to select last two characters of a string

How to select last two characters of a string

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

For example:

var member = "my name is maanu";

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

Answers:

You can pass a negative index to .slice().

var member = "my name is maanu";

var last2 = member.slice(-2);

alert(last2); // "nu"

Questions:
Answers:

Try this, note that you don’t need to specify the end index in substring.

var characters = member.substr(member.length -2);

Questions:
Answers:

now 2016 just string.substr(-2) should do the trick (not substring(!))

taken from MDN

Syntax

str.substr(start[, length])

Parameters

start

Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is
the length of the string (for example, if start is -3 it is treated as
strLength – 3.) length
Optional. The number of characters to extract.

Questions:
Answers:

You can try

member.substr(member.length-2);

Questions:
Answers:
var member = "my name is maanu";

var answer=member.substring(0,member.length - 2);

alert(answer);

Questions:
Answers:

You should use substring, not jQuery, to do this.

Try something like this:

member.substring(member.length - 2, member.length)

W3Schools (not official, but occasionally helpful): http://www.w3schools.com/jsref/jsref_substring.asp

Adding MDN link as requested by commenter: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring