- Instant help with your JavaScript coding problems

Get the last character of a string in JavaScript

Question:
How to get the last character of a string in JavaScript?
Answer:
const getLastCharacter = (text) => {
    if (!text) {
        return '';
    }
    return text.slice(-1);
}
Description:

To get the last character of a string in vanilla JavaScript is quite simple with the slice method. The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

If beginIndex is negative, slice() begins extraction from str.length + beginIndex.

However, there is a problem with this solution. That it doesn't support emojis, like in this text: test😁 If the last character is an emoji, neither the slice , nor the charAt , nor the substring method will give a satisfactory result. Fortunately, with a simple trick and the array slice method, we can also solve this problem:

const getLastCharacter = (text) => {
    if (!text) {
        return '';
    }
    return [...text].slice(-1);
}

 

Share "How to get the last character of a string in JavaScript?"
Related snippets:
Tags:
get, last, character, string, text, javascript
Technical term:
Get the last character of a string in JavaScript