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.