How to Find the Last Character of a String in JavaScript?

Estimated read time 1 min read

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");
}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply