find longest word in a string

前端 未结 3 1043
别跟我提以往
别跟我提以往 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:21

    I think the easiest solution is to split, sort the array by length and then pick the first element of the array.

    function longest(str) { 
    
     var arr = str.split(" ");
    
     var sorted = arr.sort(function (a,b) {return b.length > a.length;});
    
    return sorted[0];
    
    }
    

    If you want the length, just add .length to return sorted[0].

提交回复
热议问题