JavaScript Snippet

Count Words in a String

Difficulty: Easy

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.

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

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.