javascript get last character in string
How to Get the Last Character in a String Using JavaScript
As a web developer, I often come across situations where I need to extract the last character from a string using JavaScript. Here are a few ways to accomplish that:
Method 1: Using the charAt() method
The charAt()
method is used to get the character at a specific index in a string. To get the last character, we need to subtract 1 from the length of the string and pass that value as an argument to the charAt()
method.
let str = "Hello World!";
let lastChar = str.charAt(str.length - 1);
console.log(lastChar); // Output: "!"
Method 2: Using the substr() method
The substr()
method is used to extract a substring from a string, based on the starting and ending indexes. To get the last character, we can pass the length of the string as the starting index and 1 as the second argument.
let str = "Hello World!";
let lastChar = str.substr(str.length - 1, 1);
console.log(lastChar); // Output: "!"
Method 3: Using the slice() method
The slice()
method is also used to extract a substring from a string, based on the starting and ending indexes. To get the last character, we can pass -1 as the argument to the slice()
method, which will start from the end of the string.
let str = "Hello World!";
let lastChar = str.slice(-1);
console.log(lastChar); // Output: "!"
These are some of the ways to get the last character from a string in JavaScript. Depending on the situation, one method may be more appropriate than the others. It's important to understand the differences between them and choose the one that best fits your needs.