In this article, we are going to learn how can we get the last character of a string in JavaScript. we have given a string of size len, the task is to get the last character of a string using JavaScript.
There are several methods to solve this problem:
Table of Content
Method 1: Using charAt() Method
In this approach, we will count the number of characters in a given string by using the str.length property. Since the indexing starts from 0 use str.charAt(str.length-1) to get the last character of the string.
Example: This example implements the above approach.
// Input String let str = "GeeksforGeeks" ;
// Getting last character using char at let res = str.charAt(str.length - 1); // Display output console.log(res); |
s
Method 2: Using str.slice() Method
In this approach, we will use the string.slice() function and it will return the last character of the string.
Example: This example uses the slice() function to get the last character of the string.
// Input string let str = "GeeksforGeeks" ;
// Getting last character using slice method let res = str.slice(-1); // Display output console.log(res); |
s
Method 3: Using str.substr() Method
In this approach, we will use the str.substr method and it returns the specified number of characters from the specified index from the given string.
Example: This example uses str.substr to print the last character of the string.
// Input string let str = "GeeksforGeeks" ;
// Getting last character using substr method let res = str.substr(-1); // Display Output console.log(res); |
s
Method 4:Using JavaScript str.length for index
Using string indexing, we can use string indexing to access the element of the array and use the length property of the string to access the last element index
Example: This example uses string indexing to print the last character of the string.
// Input string let str = "GeeksforGeeks" ;
// Getting last character using str.length let res = str[str.length-1]; // Display output console.log(res); |
s
Method 5: Using String.at() method
In this method, we can pass -1 for getting the last character of the string.
Syntax:
str.at(-1)
Example: In this example, we will use str.at() for getting the last character.
// Input string let str = "GeeksforGeeks" ;
// Getting last character using string.at method let res = str.at(-1); // Display output console.log(res); |
s
Method 6: Using String.match() method
In this method, we will use regular expression for getting the last character of the given string.
Example: In this example, we will use str.match() for getting the last character.
// Input string let str = "GeeksforGeeks" ;
// Getting last charcter using match method let res = str.match(/.$/g); // Display output console.log(res); |
[ 's' ]
Time complexity: O(N), Where N is the length of the string.
Auxiliary complexity: O(1), Because no extra space is used.