[removed] find longest word in a string

前端 未结 30 2544
余生分开走
余生分开走 2020-11-27 03:50
function longestWord(string) {
    var str = string.split(\" \");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
                


        
相关标签:
30条回答
  • 2020-11-27 04:06

    TRY THIS

     function longest(string) {
            var str = string.split(" ");
            var longest = 0;
            var word = null;
            for (var i = 0; i <= str.length - 1; i++) {
                if (longest < str[i].length) {
                    longest = str[i].length;
                    word = str[i];
                }
            }
            return word;
        }
    
    0 讨论(0)
  • 2020-11-27 04:07

    Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.

    function longest(string){
        var longestWord = string.split(' ').sort(function(a,b){
            return b.length - a.length;
        });
        return longestWord[0];
    }
    
    0 讨论(0)
  • 2020-11-27 04:07

    Another method is by using sort:

        function longestWord(string) {
            let longest = 0;
            let str = str.split(" ").sort((word1,word2)=>{
            });
            return str[0].length;
       }
       longestWord('I love Python ')
    
    0 讨论(0)
  • 2020-11-27 04:09
        function findLongestWord(str) {
           let stringArray = str.split(" ");
           stringArray.sort(function(a, b){
              return a.split('').length < b.split('').length;
           })
           return stringArray[0];
        }
    
        findLongestWord("The quick brown fox jumped over the lazy dog");
    
    0 讨论(0)
  • 2020-11-27 04:09
    // My simple solution.
    
    const findLongestWordLength = str => {
        let array = str.split(" ");
        let longest = 0;
    
        array.map(e => {
            if (e.length > longest) {
                longest = e.length;
            }
        })
        return longest;
    }
    
    0 讨论(0)
  • 2020-11-27 04:10

    You can simplify your code with a library like Lo-Dash:

    function longestWord(string) {
        var words = string.split(' ');
        return _.max(words, function(word) { return word.length; });
    }
    
    0 讨论(0)
提交回复
热议问题