var str = "Hello";
var lastChar = str.charAt(str.length - 1);
console.log(lastChar); // Output: "o"
s
var str = "Hello";
var lastChar = str.charAt(str.length - 1);
console.log(lastChar); // Output: "o"
In this example, str.charAt(str.length - 1)
is used to retrieve the character at the index equal to the length of the string minus 1. Since string indices are zero-based, str.length - 1
points to the last character in the string.
Using slice()
method
var str = "Hello";
var lastChar = str.slice(-1);
console.log(lastChar); // Output: "o"
s
In this example, str.slice(-1)
is used to extract the last character of the string. The negative index -1
indicates counting from the end of the string.
Both methods provide the same result and give you the last character of the string.
s
No comments:
Post a Comment