How can I get the last character in a string? [duplicate]
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)
Solution 1:
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];
Solution 2:
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);
Solution 3:
var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
http://jsfiddle.net/MZEqD/
Solution 4:
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.
Lots of String functions explained here