The last character of a string in JavaScript can be accessed using the index string.length - 1
of the string:
var string = "Hello, World!";
var lastChar = string[string.length - 1];
console.log(lastChar); // Output: "!"
Note that if the string is empty, attempting to access its last character will result in an error. It’s a good practice to check the length of the string before accessing its characters:
if (string.length > 0) {
var lastChar = string[string.length - 1];
console.log(lastChar);
} else {
console.log("The string is empty");
}
+ There are no comments
Add yours