Skip to main content
2 of 3
Suggest better intermediate result
200_success
  • 144.2k
  • 22
  • 188
  • 473

longestword should be named using an interCaps naming convention. Also, replaced and final aren't exactly helpful variable names. However, if you were to have an intermediate result called words, it would be quite clear what that stands for.

It's good practice to terminate all statements with semicolons, even though JavaScript allows them to be omitted.

function longestWord(str){
    var words = str.replace(/[^A-Za-z\s]/g, "").split(" ");
    var wordsByDescendingLen = words.sort(function(a, b) {
        return b.length - a.length;
    });
    return wordsByDescendingLength[0];
}

Note that hyphenated words will have their hyphens dropped, both when comparing lengths and when returning the result.

200_success
  • 144.2k
  • 22
  • 188
  • 473