Dharmaraj
Dharmaraj

Reputation: 50920

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?

Upvotes: 0

Views: 1048

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50920

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

Upvotes: 1

wentjun
wentjun

Reputation: 42566

An alternative solution would be to use a regex:

const str2: string = 'I   love   stackoverflow'

console.log(str2.split(/\s+/).length);

This will ensure that multiple spaces will be splitted.

Test:

console.log('I   love   stackoverflow'.split(/\s+/).length);


console.log('Ilovestackoverflow'.split(/\s+/).length);

Upvotes: 0

Related Questions