find longest word in a string

前端 未结 3 1044
别跟我提以往
别跟我提以往 2021-01-15 05:01

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

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 05:08

    There you go:

    function longest(str) {
      var words = str.split(' ');
      var longest = ''; // changed
    
      for (var i = 0; i < words.length; i++) {
        if (words[i].length > longest.length) { // changed
          longest = words[i]; // changed
        }
      }
      return longest;
    }
    console.log(longest("This is Andela"));

提交回复
热议问题