Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to count characters in a string

Short answer

The length property holds the length of a string:

console.log('Hello'.length);

Output:

5

Emoji

length counts code units, and some symbols, such as emoji, take two. The spread operator splits a string into real characters:

const text = 'Hi 👋';
 
console.log(text.length);
console.log([...text].length);

Output:

5
4

A specific character

To count one character, split the string into characters and keep only the matching ones:

const text = 'banana';
const count = [...text].filter((char) => char === 'a').length;
 
console.log(count);

Output:

3

Without spaces

Remove the spaces with replaceAll() before counting:

console.log('a b c'.replaceAll(' ', '').length);

Output:

3

Common mistake

length is a property, not a method. With parentheses you get an error:

try {
  'Hello'.length();
} catch (error) {
  console.log(error.message);
}

Output:

"Hello".length is not a function

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.