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