I have a value "319CDXB" everytime i have to access last three characters of the Strring ho开发者_JS百科w can i do this . Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery
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.
You can do this with regular JavaScript:
var str = "319CDXB";
var lastThree = str.substr(str.length - 3);
If you're getting it from jQuery via .val(), just use that as your str in the above code.
Simple:
str = "319CDXB"
last_three = str.substr(-3)
var str = "319CDXB";
str.substr(str.length - 3); // "DXB"
精彩评论