Basic Algorithm Scripting: Find the Longest Word in a String

Basic Algorithm Scripting: Find the Longest Word in a String
0

#1

Hello all,
I have posted my code below and fee the logic is correct (all be it not the most elegant). When I run the code in another environment (brackets) I can get the largest number to console.log but not return. The free code camp site will not even run the code. Any suggestions would be appreciated;

function findLongestWordLength(str) {
  var counter =0;
  var number =[];
  var b =0;
for(var i=0; i< str.length; i++)
  if(str[i] !== ' '){
    counter +=1;
  }else{
    number[b] = counter;
    b++;
    counter = 0; 
  }

 var largest = 0   
    
for(var c =0; c <=largest ; c++){
    if(number[c] > largest){
        largest = number[c];
    }
    
}
  return largest;
  
}

#2

can you post the challenge link this is for?


#3

Here is the challenge link
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/


#4

I think the linter used is having trouble with the fact that your first for loop is not wrapped in { and }.

Once you fix that, your code still has a logic issue for the last test case of

findLongestWordLength(“What if we try a super-long word such as otorhinolaryngology”)

Your solution returns 4, when it should return 19.


#5

Wow thank you !! will keep at it but this helps a ton thanks again!


#6

Use var res = str.split(" "); to get split string at place of every " " and after just count length of every member array.