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.

Respuesta :

tonb

Answer:

function countWords(sentence) {

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

}

const sentence = 'This sentence  has five  words ';

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

Explanation:

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