JavaScript Code


How to get last character in string in JavaScript?


Get last character in string in JavaScript

In this tutorial, you are given a string. You should get the last character in the string.

Solution

To get the last character in the given string in JavaScript, use String charAt() method. charAt() method takes index as argument and returns the character at the index. If we pass (length of the string – 1) for index, then charAt() returns the last character in the string.

str.charAt(str.length - 1)

Program

1. Get the last character of the string value in str, and print it to console.

let str = 'hello world';
let firstChar = str.charAt(str.length - 1);
console.log(firstChar);