In this article, 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 some of which are discussed below:
Methods to Get the Last Character of a String:
This method returns the character at a given index.
Syntax:
character = str.charAt(index)
First, count the number of characters in a given string by using the str.length property. Since the indexing starts from 0 so 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);
|
The string.slice() function is used to return a part or slice of the given input string.
Syntax:
str.slice(startingindex, endingindex)
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);
|
The str.substr method returns the specified number of characters from the specified index from the given string.
Syntax:
str.substr( start_index, Length_sub_str );
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
Syntax:
str[ str.length-1 ];
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 can search for the last character in the string.
Syntax:
str.match(/.$/g)
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.