Gabriel Gabriel - 1 year ago 88
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download