Find the longest word in a string using javascript

后端 未结 10 1168
长情又很酷
长情又很酷 2021-01-16 23:06

I\'m trying to find the longest word in a string, but it continually returns the length of the first word. Any ideas?

Here\'s my code:

function findL         


        
10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-16 23:37

    Here is how I did it (I enclose a commented long version and a uncommented short version):

     /***************
     * LONG VERSION *
     ***************/
    function findLongestWord(str) {
      // Create an array out of the string
      var arr = str.split(' ');
    
      // Sort the array from shortest to largest string
      arr = arr.sort(function(a, b) {
        return a.length-b.length;
      });
      // The longest string is now at the end of the array
    
      // Get the length of the longest string in the Array
      var longestString = arr.pop().length;
    
      // return the lenght of the longest string
      return longestString;
    }
    
    /*****************
     * SHORT VERSION *
     ****************/
    function findLongestWord(str) {
      return str
        .split(' ')
        .sort(function(a, b) { return a.length-b.length; }) 
        .pop().length;
    }
    

提交回复
热议问题