Find the longest word in a string?

前端 未结 8 2281
旧巷少年郎
旧巷少年郎 2021-01-17 05:34

I am trying to write a basic javascript function to find the longest word in a string and log it\'s length.

So far I have:

function findLongestWord(         


        
8条回答
  •  情歌与酒
    2021-01-17 05:46

    function findLongestWord(str) {
      var arr=str.split(" ");
      var sarr=arr.sort(function(a,b){return b.length-a.length;});
      str=sarr[0];
      return str.length;
    }
    

    using the javascript Array.prototype.sort() we can slove this problem elegantly without using the loop

提交回复
热议问题