Finding longest word in a string I was working on a problem from Coderbyte. The challenge was to write a function that takes in a string and returns the longest word in the string. If two words are the same size then it asks to return the first one. The input will never be empty.

function longestword(str){
    var replaced = str.replace(/[^A-Za-z\s]/g,"");
    var final = replaced.split(" ").sort(function(a,b){return b.length - a.length})
    return final[0];
    }
longestword("This is a string theres two words that are the same size oh no!")
=&gt;'string'


What do you think about my code?
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 wordsByDescendingLength = 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.