Find the Longest Word in a String - Working normally except for one string

Tell us what’s happening:
I don’t know if any built in functions available for this but i tried to do the challenge my way and this is what i got. The code is working fine for every string except for “What if we try a super-long word such as otorhinolaryngology” Help Me guys

Your code so far


function findLongestWordLength(str) {
  let long=0;
  let curr=0;
  for (let i=0;i<str.length;i++){
    if(str[i]==' '){
      if(curr>=long){
        long=curr;
        curr=0;
      }
      else{
        curr=0;
      }
    }
    else{
      curr=curr+1;
    }
  }
  console.log(long);
  return long;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

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

You will always have problems when the last word in the string is the longest one.

This is because of the code that you are starting the loop with. It only checks curr vs long and revises long if you encounter " ". When the longest word is the last one, there isn’t any " " after it, so you cannot check if the last one is the longest one and modify your long variable accordingly. I hope that helps.

Happy coding!

Okay, Got it. :smiley::smiley: Thank You.
Happy Coding.