- Instant help with your JavaScript coding problems

Count the number of characters in a string with JavaScript

Question:
How to count the number of characters in a string with JavaScript?
Answer:
const getCharacterCount = (text) => {
    if (!text) {
        return 0;
    }
    return [...text].length;
}

const getTextLength = (text) => {
    if (!text) {
        return 0;
    }
    return text.length;
}
Description:

Counting the number of characters in a text is a relatively simple task using the length property of the string. However, when you have to support emojis, you need to pay attention as the length property of a String object contains the length of the string, in UTF-16 code units.

Since length counts code units instead of characters, if you want to get the number of characters you need a different approach where characters are counted instead of code units. To count characters in a Unicode string use the code: [...text].length  

Share "How to count the number of characters in a string with JavaScript?"
Related snippets:
Tags:
string, character, count, length, javascript, string length, character count
Technical term:
Count the number of characters in a string with JavaScript