Access the last three characters of a value in jQuery

I have the value "319CDXB" every time I have to access the last three characters of the String, how can I do this. Usually the length changes all the time. Every time I need the last characters of a string using jQuery

+6
javascript jquery
source share
4 answers

The String .slice() method allows you to use a negative index:

 var str = "319CDXB".slice( -3 ); // DXB 

EDIT:. To put it a bit, the .slice() method for String is a method that is very similar to its Array .

The first parameter represents the starting index, and the second is the index representing the breakpoint.

Any parameter allows you to use a negative index if the range makes sense. Omitting the second parameter means the end of the line.

Example: http://jsfiddle.net/patrick_dw/N4Z93/

 var str = "abcdefg"; str.slice(0); // "abcdefg" str.slice(2); // "cdefg" str.slice(2,-2); // "cde" str.slice(-2); // "fg" str.slice(-5,-2); // "cde" 

Another nice thing about .slice() is that it is widely supported in all major browsers. These two reasons make this (in my opinion) the most attractive option for getting a section of a string.

+24
source share

You can do this using regular JavaScript:

 var str = "319CDXB"; var lastThree = str.substr(str.length - 3); 

If you get it from jQuery via .val (), just use it as your string in the code above.

+4
source share

Plain:

 str = "319CDXB" last_three = str.substr(-3) 
+2
source share
 var str = "319CDXB"; str.substr(str.length - 3); // "DXB" 
+1
source share

All Articles