view raw
Gabriel Gabriel - 6 months ago 34
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;


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