Find the Longest Word - failed success

Tell us what’s happening:

This is not pretty by any means. I saw the hint about split() and smacked my own forehead, but…

This works. It returns the correct digits for all sentences, even 19 for the one with the big word. But it still fails the challenge on the sentence with the big word. Maybe because the word is at the end? It never has a chance to go through the else loop the final time to set the longestWord. That’s why the push of a space when creating the array.

All other sentences pass the challenge.

Anyone see what’s wrong?

Your code so far


function findLongestWordLength(str) {
  let longestWord = 0;
  //initialize newArray and push str in as a character array
  let newArray = [];
  for(let l in str){
    newArray.push(str[l]);
  }
  //push white space to force one last trip through else when longest word occurs at the end
  newArray.push(' ');
  //new variable to count the letters in each word
  let letterCount = 0;
  for(let i = 0; i<newArray.length;i++){
    //if a character, add to letter counter
    if(/[a-z]/i.test(newArray[i])){
      letterCount++;
      //console.log(newArray[i],letterCount);
     //when the word is finished, check if it’s the longest word 
    }else {
     if(letterCount > longestWord){
      longestWord = letterCount;
      //console.log(longestWord);
      }
      letterCount = 0;
    }
  }
  //console.log(longestWord);
  return longestWord;
}
console.log(findLongestWordLength(`What if we try a super-long word such as otorhinolaryngology`));

Your browser information:

User Agent is: Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/20.2 Mobile/15E148 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 passes all the tests for me.

Ok, what the heck? I reset the challenge and it passed for me too.

:joy: Thanks.

Couple remarks for future:

  1. String is iterable (just like array), meaning converting it to array is an easy cheesy task:
const str = 'Hello World!';
const array = [...str]; // same as Array.from(str);
  1. Your solution is more correct than all solutions in the hints, because split() should not be used here, consider this string:
const str = 'What if comma, ha?';

To be picky douchebag, your solution doesn’t account for words like super-long and com'on :slight_smile:

3 Likes

Thank you. I knew there was an easier way to handle the string.

And a great point. I actually considered the hyphen but put on my blinders since it wasn’t the longest :joy: