176k views
5 votes
Write a function named countWords that reads in a line of text into a string variable, counts and returns the number of words in the line. For simplicity assume that the line entered only has characters and spaces.

1 Answer

6 votes

Answer:

function countWords(sentence) {

return sentence.match(/\S+/g).length;

}

const sentence = 'This sentence has five words ';

console.log(`"${sentence}" has ${countWords(sentence)} words` );

Step-by-step explanation:

Regular expressions are a powerful way to tackle this. One obvious cornercase is that multiple spaces could occur. The regex doesn't care.

User Yosef Tukachinsky
by
5.0k points