Gabriel Gabriel - 1 month ago 10
Javascript Question

Find the longest word in a string using javascript

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 findLongestWord(str) {
var words = str.split(' ');
var longest = 0;

for (var i=0;i<words.length;i++) {
if (words[i].length > longest) {
longest = words[i].length;
}

return longest;
}
}

Answer

Your return statement should be outside the for loop. It only executes the first loop then bails out.

Comments