Skip to main content

Count the number of words in a string

JavaScript version

const countWords = (str) => str.trim().split(/\s+/).length;

TypeScript version

const countWords = (str: string): number => str.trim().split(/\s+/).length;

Examples

countWords('Hello World'); // 2
countWords('Hello World'); // 2
countWords(' Hello World '); // 2

Comments