Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Word Count undefined problem (JavaScript)
    My code is below. I keep on getting the error that it cannot read the match property for undefined. Why doesn't the program recognize the letter variable?
    function WordCount(str) { 
    	
      str = " " + str + " "; 
      var hits = 0;
      for (var i = 0; i < str.length; i++) {
          if (str[i] === " ") {
          var letter = str[i + 1];
          if (letter.match(/[a-z]/i)!= null) {
            hits += 1;
          }
        }
      }
      
      
      return hits; 
             
    }
    
    voyenavion posted this question on 12/1/15 | word, count, javascript
    Answers
  • +
  • 1
  • -
  • In the last 'for' iteration when 'i' is equal to (str.length - 1) you try to access to string by index that out of range (cause i + 1 == str.length - 1 + 1 == str.length). So ffter this assignment:
    var letter = str[str.length]
    the 'letter' variable is undefined.
  • +
  • 0
  • -
  • I guess you're trying to count the words on a string. Why don't you use .split()? That creates an array of elements splitting by the character you wish. If you use and space (" "), that will create an array of words. Checking that array length you can easily get the number of words in your input string.
    function countwords2(str) { 
      str =str.split(" "); 
      return str.length; 
    }
    
    Log in to write an answer.