Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Longest word challenge
    Hey guys, I'm working on the longest word challenge in javascript but whenever I run the program, the variable answer is remaining empty. What am I doing wrong? -Brian
    function LongestWord(sen) { 
    
    var words = sen.split(" ");
    
    var longest = 0;
    
    var answer = "";
    
      for(var i; i<words.length; i++) {
    
        words[i] = words[i].replace(/[^a-zA-Z]+/g, "");
    
        if(words[i].length>longest) {
    
          longest = words[i].length;
    
          answer = words[i];
    
        }
    
      }
    
      return answer; 
    
    }
    th3crazed posted this question on 12/16/13 | javascript, longest, word
    Answers
  • +
  • 7
  • -
  • Check out your for loop youre missing var i = 0. You haven't set it to anything
  • +
  • 6
  • -
  • function LongestWord(sen){
     sen = sen.split(/[^a-zA-Z]/);  
      return sen.sort(function(a,b){return b.length-a.length})
                .shift(); 
    }
    
  • +
  • 1
  • -
  • As a side note, you would also want to fix the code for your regex
    //words[i] = words[i].replace(/[^a-zA-Z]+/g, "");
    words[i] = words[i].replace(/[^a-z0-9]+/gi, "");
    The challenge may also have integers. Replaced A-Z with the i flag so the matches are case insensitive.
  • +
  • -2
  • -
  • also consider the correction of your for loop to for(var i=0; i<=words.length; i++)
    Log in to write an answer.