Find the Longest Word in a String (Problem with the dash(-))

Hey everyone,

My code gives a right output for all kind of string. But it comes to problem when the string have a dash(-). For example in this code, it will return 10 which is I guess it only takes the word “super-long” as the longest word in that string instead of “otorhinolaryngology”. Why is this happening? Why it stop looping for the next word?


function findLongestWordLength(str) {
var total = 0;
var most = 0;


for(var i = 0 ; i < str.length ; i++) {

  if (str[i] != " ") {
    total++
  }

  else if (str[i] == " ") {

    if (total > most) {
      most = total
      total = 0
    }
    else {
      total = 0
    }

  }
  

}

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

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36

Challenge: Find the Longest Word in a String

Link to the challenge:

Notice when your code updates the “most” variable. The problem is not the dash - the code does loop until the end of the string.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.