Code Snippets
/

Count Words in a String

Count Words in a String

Word counting drives reading-time estimates, character-budget warnings, and SEO meta-checks. The naive `str.split(' ').length` overcounts double spaces, miscounts empty input, and ignores non-Latin scripts entirely. This snippet starts with a regex-based whitespace split, hardens it against empty and whitespace-only input, then upgrades to `Intl.Segmenter` for locale-aware counting in Chinese, Japanese, and Thai where there are no spaces.

JavaScript
Easy
3 snippets
strings
regex
utility

827 views

22

function wordCount(str) {
    if (typeof str !== 'string') return 0;
    return str.trim().split(/\s+/).filter(Boolean).length;
}

console.log(wordCount('Hello world'));                // 2
console.log(wordCount('  Many   spaces   between ')); // 3
console.log(wordCount(''));                           // 0
console.log(wordCount('   '));                        // 0

Splitting on /\s+/ collapses any run of whitespace (spaces, tabs, newlines) into a single delimiter, which fixes the naive split(' ') overcount on double spaces. The leading trim() strips surrounding whitespace so the split does not produce a phantom empty leading entry, and the filter(Boolean) is a belt-and-braces against the rare case where split still emits an empty string. Empty and whitespace-only input correctly return 0 because trim() reduces them to '' and ''.split(/\s+/) yields [''], which the filter removes. Use this for English-style text where words are space-separated.