How to get the last character of a string in JavaScript ?
Last Updated :
29 Nov, 2023
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:
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str.charAt(str.length - 1);
console.log(res);
|
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str.slice(-1);
console.log(res);
|
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str.substr(-1);
console.log(res);
|
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str[str.length-1];
console.log(res);
|
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str.at(-1);
console.log(res);
|
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.
Javascript
let str = "GeeksforGeeks" ;
let res = str.match(/.$/g);
console.log(res);
|
Time complexity: O(N), Where N is the length of the string.
Auxiliary complexity: O(1), Because no extra space is used.
Share your thoughts in the comments
Please Login to comment...