How to get last character of a string in JavaScript
In this post we will give you information about How to get last character of a string in JavaScript. Hear we will give you detail about How to get last character of a string in JavaScriptAnd how to use it also give you demo for it if it is necessary.
we will learn two different ways to get the last character of a string in JavaScript.
In JavaScript, strings are the sequence of characters, where the index of the first character is 0, the second character is 1, third character is 3 and last character index is string.length-1 etc.
1. Using charAt() method
To get the last character of a string in JavaScript, we can use the built-in charAt() method by passing string.length-1 as an argument to it.
The string.length-1 returns the index of a last character.
Here is an example:
const str = "hello";const lastCharacter = str.charAt(str.length-1);console.log(lastCharacter); // "o"
2. Using slice() method
If we pass -1 as an argument to the slice() method we can get the last character of a string.
const string = "hello";const lastCharacter = string.slice(-1);console.log(lastCharacter); // "o"
Note: Negative index -1 is same as string.length-1.
Hope this code and post will helped you for implement How to get last character of a string in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs