Search code examples
stringtypescript

How do I count number of words in a string in Typescript without counting extraneous spaces?


I have seen many cases where people sometimes rely on whitespaces which causes some miscalculations.

For Example, take 2 strings;

const str1: string = 'I love stackoverflow'
const str2: string = 'I   love   stackoverflow'

Using the numOfWhitespaces + 1 thing gives wrong number of words in case of str2. The reason is obvious that it counts 6 number of spaces.

So what should be an easy and better alternative?


Solution

  • The shortest would be using: str1.split(/\s+/).length