find longest word in a string

Viewed 1544

Currently trying to figure out how to find the longest word in as string and my research has gotten me somewhere. I found a code on SO that shows the amount of alphabets in the longest word

Example

function longest(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;
}
longest("This is Andela");

//This returns 6

How do i edit this code such that it returns the word instead of the amount of alphabets.That is

//Returns Andela instead of 6

Considering i am also new to javascript

3 Answers

I recommend this approach:

function LongestWord(text) {
    return text
      .split(/\s+/g)
      .reduce(function (record, word) {
        if (word.length > record.length) {                  
          record = word;
        }
        return record;
      }, '');
}
console.log(LongestWord('In this sentence it is not obvious which is the longest word.'));

If you want to return the length of the longest word, just add .length to the end of the return.

Related