Book
Submodule 8.3: Word count
Submodule 8.3: Word count
Completion requirements
View
- JavaScript word counter
Exercise
Exercise
Redesign your JavaScript file so that extra consecutive whitespaces are not counted.
Tip: The variable sum should increase if the inserted character is not the white space
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function(){
var i=0;
sum=0;
var myValue = document.getElementById("myWordsToCount").value;
var res = myValue.split(" ");
while (i<res.length) {
/* The variable sum increases if the inserted character is not the white space*/
if (res[i] != "") {
sum=sum+1;
}
i=i+1;
}
document.getElementById("wordcount").innerHTML = sum;
console.log(res, i, res.length);