Javascript Algorithm String find the longest word

Description

Javascript Algorithm String find the longest word

function longest_word(string)
{
  var words = string.split(' ');
  var count = 0;/*  ww w. j  av a  2 s. c  o  m*/
  for(var i = 0; i < words.length; i++)
    {
      count++;
    }
  if(count < 2)
    {
      return "The longest word is" + words[0];
    }
  else
    {
      var max = words[0];
      for(var j = 0; j < words.length; j++)
        {
          if(words[j].length > max.length)
            {
              max = words[j];
            }
        }
      return max;
    }
  
}
console.log(longest_word("dinosaur cat hat"));



PreviousNext

Related