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 wordsByDescendingLenwordsByDescendingLength = 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.