I\'m trying to find the longest word in a string, but it continually returns the length of the first word. Any ideas?
Here\'s my code:
function findL
Here is how I did it (I enclose a commented long version and a uncommented short version):
/***************
* LONG VERSION *
***************/
function findLongestWord(str) {
// Create an array out of the string
var arr = str.split(' ');
// Sort the array from shortest to largest string
arr = arr.sort(function(a, b) {
return a.length-b.length;
});
// The longest string is now at the end of the array
// Get the length of the longest string in the Array
var longestString = arr.pop().length;
// return the lenght of the longest string
return longestString;
}
/*****************
* SHORT VERSION *
****************/
function findLongestWord(str) {
return str
.split(' ')
.sort(function(a, b) { return a.length-b.length; })
.pop().length;
}