First, I know I can probably do this with built in functions, but I wanted to try this way first… The challenge is “Find the Longest Word in a String”
The code works sometimes… But there’s something wrong and I cannot find what… Can someone help?
function findLongestWord(str) {
//transformar em array
//a cada espaço, recomeçar a contar
//comparar com contagem da palavra anterior
var array = str.split('');
var thisWord = 0;
var longest = 0;
for(var i=0; i<array.length-1;i++){
if(array[i] == " "){
thisWord--;
if(thisWord > longest){
longest = thisWord;
}
thisWord = 0;
}
thisWord++;
}
return longest;
}
var ret = findLongestWord("Fui no tororo");
console.log(ret);