Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access the last three Characters of the value in Jquery

I have a value "319CDXB" everytime i have to access last three characters of the Strring how can i do this . Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery

like image 497
Someone Avatar asked Dec 08 '10 22:12

Someone


1 Answers

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

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

EDIT: To expound a bit, the .slice() method for String is a method that behaves very much like its Array counterpart.

The first parameter represents the starting index, while the second is the index representing the stopping point.

Either parameter allows a negative index to be employed, as long as the range makes sense. Omitting the second parameter implies the end of the String.

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"

The other nice thing about .slice() is that it is widely supported in all major browsers. These two reasons make it (in my opinion) the most appealing option for obtaining a section of a String.

like image 87
user113716 Avatar answered Oct 06 '22 01:10

user113716