How to count characters in a string
Short answer
The length property holds the length of a string:
console.log('Hello'.length);Output:
5Emoji
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
4A 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:
3Without spaces
Remove the spaces with replaceAll() before counting:
console.log('a b c'.replaceAll(' ', '').length);Output:
3Common 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 functionFunctions used in this recipe
- String.prototype.length — The length of a string — how many characters it has.
- String.prototype.split — Splits a string into an array by a separator.
- Array.prototype.filter — Creates a new array from the elements that pass a test.