Find the Longest Word in a String

Return the length of the longest word in the provided sentence.

Your response should be a number.

function findLongestWord(str) {
return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

Hints:

We need to create a variable that holds the longest word in the sentence. Then we need to loop through the whole sentence and check the length of each word. If the length of the word is greater than our variable, then reassign that word length to our variable.

1. Create a variable called longestWord

function findLongestWord(str) {
var longestWord = 0;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2. Split up the sentence with String.prototype.split() method

function findLongestWord(str) {
var longestWord = 0;
str = str.split(' ');
}

3. Loop through the sentence

function findLongestWord(str) {
var longestWord = 0;
str = str.split(' ');
for (var i = 0; i < str.length; i++) {

}
}

4. If the length of each word is greater than the longestWord, then reassign it to the longesWord

function findLongestWord(str) {
var longestWord = 0;
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
if (str[i].length > longestWord) {
longestWord = str[i].length;
}
}
}

5. Return the longestWord outside of the for loop

function findLongestWord(str) {
var longestWord = 0;
str = str.split(' ');
for (var i = 0; i < str.length; i++){
if (str[i].length > longestWord){
longestWord = str[i].length;
}
}
return longestWord;
}

Conclusion

This is a great problem to practice using the for loop. Also, a good way to make use of a variable to check each value in a loop.

Next up Title Case a Sentence.