How can I get the last character in a string?

JavascriptJqueryString

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

 var myString = "Test3";
 alert(myString[myString.length-1])

here is a simple fiddle

http://jsfiddle.net/MZEqD/

Solution 4 - Javascript

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

Solution 5 - Javascript

myString.substring(str.length,str.length-1)

You should be able to do something like the above - which will get the last character

Solution 6 - Javascript

Use the charAt method. This function accepts one argument: The index of the character.

var lastCHar = myString.charAt(myString.length-1);

Solution 7 - Javascript

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - JavascriptJamie DixonView Answer on Stackoverflow
Solution 2 - JavascriptArnaud Le BlancView Answer on Stackoverflow
Solution 3 - JavascriptJohn HartsockView Answer on Stackoverflow
Solution 4 - JavascriptJoeView Answer on Stackoverflow
Solution 5 - JavascriptdiagonalbatmanView Answer on Stackoverflow
Solution 6 - JavascriptRob WView Answer on Stackoverflow
Solution 7 - JavascripthmertView Answer on Stackoverflow