Reputation: 50920
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
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