Find the Longest Word in a String 4

Tell us what’s happening:
// I dont know why its not returning req answer . some cases are getting passed while some are not please help.

Your code so far


function findLongestWordLength(str) {
  
  var str3;
  var str2=str.split(" ");
  for(var i=0;i<str2.length-1;i++){
    if(str2[i+1].length>=str2[i].length){
        str3=str2[i+1];    
    }
    else str3=str2[i];

  }
  return str3.length;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 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/

@Hims, you’re close! The logic you need to add is some way to check whether str3 or str2[i] is longer. Currently, the code only checks whether str2[i] or str2[i+1] is longer.

1 Like

Here is what i did.

Split str by the space. No need to create a new variable.

Defined a variable in which i will store the longest word i encounter.

Looped through str and checked if str[i] is longer (.length) then my longest word variable.

I then return that longest variable after the loop.

1 Like