How to Get Last Character from String in Javascript

Here are six ways to get the last character from a string in JavaScript:

  1. Using str.charAt()
  2. Using str.slice()
  3. Using str.substr()
  4. Using string.length
  5. Using str.at()
  6. Using str.match()

Method 1: Using str.charAt()

The indexing in a string starts from 0, and that’s why the str.charAt(str.length-1)” method is used to get the last character of the string.

const string = "Javascript is beautiful";

// last character
console.log("Last character:", string.charAt(string.length - 1));

Output

Last character: l

Method 2: Using slice()

String slice() method extracts a part of a string. It returns the extracted part in a new string, not changing the original string.

const string = "Javascript is beautiful";
// last character
console.log("last char : ", string.slice(-1));

Output

last char : l

Method 3: Using substring()

String.substring() method extracts characters between two indices (positions) from a string and returns the substring.

const string = "Javascript is beautiful";

// last character
console.log("last char : ", string.substring(string.length - 1));

Output

last char : l

Method 4: Using string. length

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.

// Input string
let str = "AppDividend";
 
// Getting last character using str.length
let res = str[str.length-1];
 
// Display output
console.log(res);

Output

d

Method 5: Using the String.at()

In this method, we can pass -1 to get the last character of the string.

// Input string
let str = "AppDividend";
 
// Getting last character using str.length
let res = str.at(-1)
 
// Display output
console.log(res);

Output

d

Method 6: Using the str.match()

In this method, we can search for the last character in the string.

// Input string
let str = "AppDividend";
 
// Getting last character using str.length
let res = str.match(/.$/g)
 
// Display output
console.log(res);

Output

[ 'd' ]

That’s it!