Javascript: find longest word in a string

Here this is your solution with a forEach, this will help you avoid the error in the future

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    return word;
}
console.log(longestWord("pride and prejudice"));

Your original problem was just the str.length - 1 should have just been str.length, originally you wouldn't have gotten to the last element of the array


One advantage to taking a functional approach to such problems is that you don't even have to keep count

See MDN Array.reduce for more info. (note: reduce needs shim for IE8)

function longer(champ, contender) {
  return (contender.length > champ.length) ? contender : champ;
}

function longestWord(str) {
  var words = str.split(' ');
  return words.reduce(longer);
}

console.log(longestWord("The quick brown fox jumped over the lazy dogs"));

That's because you're not comparing all the items in the array, you leave out the last one.

for (var i = 0; i < str.length - 1; i++)

should be

for (var i = 0; i < str.length; i++)

or

for (var i = 0; i <= str.length - 1; i++)

Tags:

Javascript