- Instant help with your JavaScript coding problems

Count the number of words in a string using JavaScript

Question:
How to count the number of words in a string using JavaScript?
Answer:
const getWordCount = (text) => {
    if (!text) {
        return 0;
    }

    return text.split(/\s+/).length;
}
Description:

Counting the number of words in a string using vanilla JavaScript can be easily solved with the split method.

The split() method divides a string into a list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

The separator can be a simple string or it can be a regular expression. When found, the separator is removed from the string, and the substrings are returned in an array.

When counting spaces, attention should also be paid to cases where the text contains several space characters in a row. Therefore, a simple single-space separator does not always give a satisfactory result. Therefore use the regular expression \s+

 

Share "How to count the number of words in a string using JavaScript?"
Related snippets:
Tags:
words, string, number, number of words, words in string, javascript, count words
Technical term:
Count the number of words in a string using JavaScript