JavaScript Code

How to get last character in string?


Problem Statement

given a string, get the last character in the string

Solution

to get the last character in the given string, 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

get the last character of the string value in str

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