Just wanted to point out that @200_success's review is excellent, but personally I would go for reduce
:
function longestWord2(str){
var words = str.replace(/[^A-Za-z\s]/g, "").split(" ");
var longestWord = words.reduce( function( longestSoFar, currentWord ) {
return currentWord.length > longestSoFar.length ? currentWord : longestSoFar;
},"");
return longestWord;
}
document.write( longestWord2( 'Code Review welcomes you' ) );
function longestWord2(str){
var words = str.replace(/[^A-Za-z\s]/g, "").split(" ");
var longestWord = words.reduce( function( longestSoFar, currentWord ) {
return currentWord.length > longestSoFar.length ? currentWord : longestSoFar;
},"");
return longestWord;
}
document.write( longestWord2( 'Code Review welcomes you' ) );
Using reduce
will access each word only once. It will also return the first word of the largest length if there are multiple words with the same largest length;