If I have the following variable in javascript
var myString = "Test3";
what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
It does it:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
This also works:
myString.charAt(myString.length-1);
And this too:
myString.slice(-1);
substr according to developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…slice. As 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. If at all possible, use the substring() method instead. - From MDN.substr( -1 ) or .splice( -1 ) wins, but even the usually slowest .split( ' ' ).pop( ) won one time for me. var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
Javascript strings have a length property that will tell you the length of the string.
Then all you have to do is use the substr() function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length - 1);
edit: yes, or use the array notation as the other posts before me have done.
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
10 characters and it worked for me myString.substring(str.length,str.length-10). Thanks buddy!myString.substring(str.length-10,str.length)myString.substring(myString.length,myString.length-10) or myString.substring(myString.length-10, myString.length) both returns the same results. Last 10 characters.
.substr( -1 )or.splice( -1 )wins, but even the usually slowest.split( ' ' ).pop( )won one time for me.