check for longest word in string javascript code example
Example 1: javascript find the longest word in a string
function findLongestWordLength(str) {
let words = str.split(' ');
let maxLength = 0;
for (let i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Example 2: js find longest vword
function findLongestWord(str) {
var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");