How to get the last character of a string in JavaScript?
Given a string of size len, the task is to get the last character of a string. There are many methods to solve this problem some of them are discussed below:
Method 1: Using charAt() function: This function returns the character at given index.
Syntax:
character = str.charAt(index)
First count number of characters in a given string by using str.length function. Since the indexing starts from 0 so use str.charAt(str.length-1) to get the last character of string.
Example:
<!DOCTYPE html> < html > < head > < title > Get the last character of a string </ title > </ head > < body > < h3 >Given String: GeeksforGeeks</ h3 > < p > Click on button to display the last character </ p > < button onclick = "myGeeks()" > Click Here! </ button > < p id = "GFG" style = "font-size:30px; color:green;" ></ p > <!-- Script to return the last character of string --> < script > function myGeeks() { var str = "GeeksforGeeks"; var res = str.charAt(str.length-1); document.getElementById("GFG").innerHTML = res; } </ script > </ body > </ html > |
Output:
- Before Clicking on the button:
- After Clicking on the button:
Method 2: Using str.slice() function: 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 slice() function to get the last character of string.
<!DOCTYPE html> < html > < head > < title > Get the last character of a string </ title > </ head > < body > < h3 >Given String: GeeksforGeeks</ h3 > < p > Click on button to display the last character </ p > < button onclick = "myGeeks()" > Click Here! </ button > < p id = "GFG" style = "font-size:30px; color:green;" ></ p > <!-- Script to return the last character of string --> < script > function myGeeks() { var str = "GeeksforGeeks"; var res = str.slice(-1); document.getElementById("GFG").innerHTML = res; } </ script > </ body > </ html > |
Output:
- Before Clicking on the button:
- After Clicking on the button: