293

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.

Mo.
  • 26,306
  • 36
  • 159
  • 225

10 Answers10

621

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"
idkwhatsgoingon
  • 658
  • 4
  • 22
  • 12
    `slice()` reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice – Offirmo Oct 30 '13 at 09:20
29

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.

halfbit
  • 3,773
  • 2
  • 34
  • 47
  • 1
    "Microsoft's JScript does not support negative values for the start index. To use this feature in JScript, you can use the following code..." - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr (whereas for slice they don't have any polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) – George Birbilis Jun 03 '18 at 21:48
  • 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 https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/scripting-articles/6w1bzf9f%28v%3dvs.84%29 – George Birbilis Jun 05 '18 at 13:20
26

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

var characters = member.substr(member.length -2);
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Your original answer was probably more appropriate. According to [MDN's `substr` docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr), *"Microsoft's JScript does not support negative values for the start index."* –  May 24 '12 at 17:03
17

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'
Liam
  • 6,517
  • 7
  • 25
  • 47
9

You can try

member.substr(member.length-2);
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • You missed member.length from your starting index :) – Mathew Thompson May 24 '12 at 16:51
  • Ah cool, I've updated my answer to reflect, thanks T.J and Ibu :) – Mathew Thompson May 24 '12 at 16:57
  • 1
    @T.J.Crowder: Pretty sure the negative index as a starting position doesn't work for IE8 and lower. –  May 24 '12 at 17:00
  • 1
    @amnotiam: **Thank you,** very good to know! I just [tested](http://jsbin.com/epogey), 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! :-) – T.J. Crowder May 24 '12 at 17:25
3

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

var result = number.toString().slice(-2);
Harijs Krūtainis
  • 1,261
  • 14
  • 13
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

Matt
  • 477
  • 1
  • 5
  • 19
  • 3
    please provide links to an official documentation such as MSDN or MDN, not w3fools :) – jbabey May 24 '12 at 17:04
  • 2
    w3schools is not "official" but generally has reliable information. MSDN is official, but is IE specific and does not have anything to do with Firefox, Safari, etc. – Matt May 24 '12 at 18:45
  • added the link to the comment as you were posting this – Matt May 24 '12 at 19:11
2
var member = "my name is maanu";

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

alert(answer);
Biju s
  • 420
  • 1
  • 7
  • 16
  • 1
    What does the code do? Please write an explanation of what this achieves. – DNKROZ Jun 19 '14 at 11:57
  • 3
    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. – anaximander Jun 19 '14 at 12:01
  • 1
    code output will be 'nu' . Take last 2 charecter from word . – Biju s Jun 23 '14 at 11:06
  • 7
    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. – ewino Mar 08 '15 at 10:28
2

Shortest:

str.slice(-2)

Example:

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

console.log(last2);
chickens
  • 19,976
  • 6
  • 58
  • 55
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.`);
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45