patternjavascriptModerate
Finding longest word in a string
Viewed 0 times
longestwordstringfinding
Problem
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.
What do you think about my code?
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!")
=>'string'What do you think about my code?
Solution
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.
Code Snippets
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];
}Context
StackExchange Code Review Q#65049, answer score: 16
Revisions (0)
No revisions yet.