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.
Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.
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"
EDIT: 2020: use string.slice(-2)
as others say - see below.
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.
EDIT 2020
MDN says
Warning: Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future.
Try this, note that you don't need to specify the end index in substring
.
var characters = member.substr(member.length -2);
The following example uses slice()
with negative indexes
var str = 'my name is maanu.';
console.log(str.slice(-3)); // returns 'nu.' last two
console.log(str.slice(3, -7)); // returns 'name is'
console.log(str.slice(0, -1)); // returns 'my name is maanu'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With