there is a problem, with my logic because when there is empty string then it adds 1 and for string with spaces it counts no. of spaces. I need to change my approach. Please guide me in right direction little bit.
you will need to consider a different approach, it seems that counting spaces doens’t work
even if you don’t know how to code it, if you can describe the logic, we can start from somewhere
Yes but the solution provided after passing test is very different, I don’t even understand that.
This code was provided-
function getWordCount(sentence) {
if (sentence.trim() === '') {
return 0;
}
const words = sentence.trim().split(/\s+/);
return words.length;
}```
And i don't understand this part at all-
split(/\s+/)
The trim() method removes leading and trailing spaces from the input string.
If the string is something like " " or " word ", trim() ensures we are working only with the actual content, excluding spaces at the start or end.
After trimming, the string is split into words using .split() and a regular expression (/\s+/). /\s+/ is a regular expression that matches one or more whitespace characters (spaces, tabs, line breaks).
It ensures that even multiple consecutive spaces between words are treated as a single separator.
After splitting the string into words, the function returns the length of the resulting array, which corresponds to the total number of words in the string.