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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With