xxxxxxxxxx
function countWords(str) {
let counts = {};
let words = str.split(' ');
for (let word of words) {
if (word.length > 0) {
if (!(word in counts)) {
counts[word] = 0;
}
counts[word] += 1;
}
}
return counts;
}
xxxxxxxxxx
var str = "your long string with many words.";
var wordCount = str.match(/(\w+)/g).length;
alert(wordCount); //6
// \w+ between one and unlimited word characters
// /g greedy - don't stop after the first match
xxxxxxxxxx
function calculateWordCount(text) {
const wordsArr = text.trim().split(" ")
return wordsArr.filter(word => word !== "").length
}
xxxxxxxxxx
const str = "hello world";
console.log(str.split(' ').length); // @output 2