Short and sweet and elegant.
Unfortunately, there can be some issues with it.
Correctness
If two word are the same size then it asks to return the first one.
The implementation will only guarantee this if the sort
implementation is stable.
That is, during sort, the relative ordering of equal elements must not change,
otherwise the original first longest string might get moved.
It seems modern browsers all use stable sort, but this was not always the case,
and the relevant documentation can be hard to find.
Performance
The time complexity of sorting is usually \$O(n \log(n))\$ at best. Using sort makes your implementation elegant but inefficient because you don't actually need to sort, you can do better. You can walk through the elements in pass and record the longest string you find.
That way the solution will be \$O(n)\$.
Non-English characters
The current implementation discards non-English characters like éèà
,
so the result can be incorrect for French, German, Hungarian texts, for example.
Formatting, coding style
These are just nitpicks, but the code would be somewhat easier to read if you follow these recommendations (borrowing from standards in other languages like Java, Python):
- Put a space before opening braces
- Put a space after commas
- Align the closing brace with the start of its statement
- Either use semicolon to end all statements always or never, do it consistently. (Related article)
Like this:
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];
}
Note: in addition, use better names as @200_success explained in his answer.