Skip to content

Get last character of string JavaScript | Example code

  • by

Use charAt() method to get the last character of the string in JavaScript. The first character in the string has an index of 0, so the last character in the string has an index of str.length - 1.

myString.charAt(myString.length-1);

Since in Javascript a string is a char array, you can access the last character by the length of the string.

myString[myString.length -1];

Get the last character of string JavaScript

Simple example code.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>

    const str = 'ABCED';

    const last = str.charAt(str.length - 1);
    console.log("Last cahr: ",last);

  </script>
</body>
</html>

Output:

Get last character of string JavaScript

Let’s use bracket notation to get the last character of a string.

const str = 'abcde';

const last = str[str.length - 1];
console.log(last); // e

Uses the slice() function to get the last character of the string.

const str = 'ABCED';

var res = str.slice(-1);
console.log(res); // D

Do comment if you have any doubts or suggestions on this JS char code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *