So I set up the split and used regex in the array to not have all the single letters become items. I then split them and I want to use a loop to iterate through the elements of the array. My problem is how do I compare the values in the array, I mean I have got them to iterate and if I change if(split[i].length) { to if(split[i].length>5) { then it passed all the cases except two. But that is hardcoding and I want to iterate through the words and compare all the words and have the longest one picked and returned in the form of a number (it’s length). Thanks!
function findLongestWordLength(str) {
const regex=/\s*\W/
let split = str.split(regex)
for (let i=0;i<split.length;i++){
if(split[i].length) {
return split[i].length
}
}
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.
here you are just checking if the length is a number different from 0
you need to save a value to use in your compare.
let’s see if a little tale could work:
you check the first word, its length is 3, it’s the highest you have found so far so you keep it. then you check the second work, the length is 5, you compare to the saved value, and as 5 is higher than 3 you keep the 3. Third word, length is 5, 5 is not bigger than 5, so you just keep previous number. Fourth word, the length is 3, as 3 is not bigger than 5 you keep the five… and so on when you have finished the sentence you can be sure that your saved number is the length of the longest word