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

Solution:

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);