Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 311
Mo. Avatar asked Oct 05 '22 06:10

Mo.


People also ask

How do I get the last 3 characters of a string?

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.

How do you get the last few characters of a string?

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.

How do you pull the last two characters in Python?

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.


4 Answers

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"
like image 576
5 revs, 3 users 60%user1106925 Avatar answered Oct 12 '22 03:10

5 revs, 3 users 60%user1106925


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.

like image 29
halfbit Avatar answered Oct 12 '22 03:10

halfbit


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

var characters = member.substr(member.length -2);
like image 25
mattytommo Avatar answered Oct 12 '22 02:10

mattytommo


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'
like image 16
Liam Avatar answered Oct 12 '22 04:10

Liam