317

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.

10 Answers 10

660

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"
Sign up to request clarification or add additional context in comments.

Comments

31

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.

2 Comments

"Microsoft's JScript does not support negative values for the start index. To use this feature in JScript, you can use the following code..." - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… (whereas for slice they don't have any polyfill: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
note that JScript is not inside the browser, it's a scripting language for working with Windows Script Host automation mainly (similar to VBScript), so it's logical that at its time it didn't include such methods.Newer Windows versions promote PowerShell, with a cryptic syntax. Anyway the comment was on slice being better candidate than substr in the case of JScript, since it supports negative indices learn.microsoft.com/en-us/previous-versions/windows/…
26

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

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

1 Comment

Your original answer was probably more appropriate. According to MDN's substr docs, "Microsoft's JScript does not support negative values for the start index."
18

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'

Comments

9

You can try

member.substr(member.length-2);

2 Comments

@T.J.Crowder: Pretty sure the negative index as a starting position doesn't work for IE8 and lower.
@amnotiam: Thank you, very good to know! I just tested, and sure enough, didn't work on IE7 or IE8 (and so presumably wouldn't work on IE6). IE9 in standards mode was fine (but not compat). I never use substr, and now I wish I could find the thread where some smug git gave me a hard time for that (and in particular not using negative indexes) -- I can now justify it! :-)
3

If it's an integer you need a part of....

var result = number.toString().slice(-2);

Comments

2

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

Comments

2
var member = "my name is maanu";

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

alert(answer);

4 Comments

What does the code do? Please write an explanation of what this achieves.
To be fair, the question is very specific about what the code needs to do, so an answer consisting of (in essence) one line of code is pretty self-explanatory.
code output will be 'nu' . Take last 2 charecter from word .
Seems to me like the code output will be "my name is maa" (everything ~except~ the last two letter), which is not what the question asked for, if I understood it correctly.
2

Shortest:

str.slice(-2)

Example:

const str = "test";
const last2 = str.slice(-2);

console.log(last2);

Comments

1

Slice can be used to find the substring. When we know the indexes we can use an alternative solution like index wise adder. Both are taking roughly the same time for execution.

const primitiveStringMember = "my name is Mate";

const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object


/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/

//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);


//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.