Return the length of the longest word in a string

Tell us what’s happening:

Okay, so below is the code I wrote. It works for all the tests but oddly fails for the last test which has a really long word in the string. What am I missing? :neutral_face:
Your code so far


function findLongestWordLength(str) {

let strArr = [...str];

let count = 0;
let newCount = 0;

for(let i = 0; i < strArr.length; i++) {
  if(strArr[i] != " ") {
    count += 1;
  } else if(strArr[i] == " " && newCount < count) {
    newCount = count;
    count = 0;
  } else {
    count = 0;
  }
}

return newCount;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15.

Challenge: Find the Longest Word in a String

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

Your code doesn’t actually check the last word in any case, because of how the if-statements check for a space character.

You could try to split the string into words instead of characters and check these …

(Did I say “check” already? :sweat_smile:)

Why then is it working for the other tests? Can you explain more? TIA.

Because in the other tests the last word isn’t the longest one. So it doesn’t matter that the last word isn’t counted.

1 Like

Ooooooohhhhhh. Fascinating! Thank you! On it!

So I tried a little something but it still didn’t work.

function findLongestWordLength(str) {

  let strArr = [...str];
  
  let count = 0;
  let newCount = 0;

  for(let i = 0; i <= strArr.length; i++) {
    if(strArr[i] != " ") {
      count += 1;
    } else if((strArr[i] == " " || strArr[i] == undefined) && newCount < count) {
      newCount = count;
      count = 0;
    } else {
      count = 0;
    }
  }

  return newCount;
}

console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));

As you can see, I added a condition that states that newCount will be updated to count only if -

if((strArr[i] == " " || strArr[i] == undefined) && newCount < count)

With the for loop running for i <= strArr.length, shouldn’t the modification work? When it is at the last letter of the string, it will try strArr[strArr.length] which will be undefined so it should check the count as usual.

No matter. Got it! I had to change the first if condition as well to -

strArr[i] != " " && strArr[i] != undefined

Thanks so much!

You may want to learn about the split() method:

1 Like

Hey thanks! I’ll check it out! :slight_smile: