Find the longest word in a string using javascript

后端 未结 10 1170
长情又很酷
长情又很酷 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条回答
  • here is how I did it.

    function findLongestWord(str) {
      var strArray =[];
      var numArray=[];
      var sortedNumArray=[];
    
      strArray = str.split(" ");
    
      numArray = strArray.map(function(val){return val.length;});
    
      sortedNumArray=numArray.sort(function(a,b){return a-b;});
    
      return sortedNumArray.pop();
    
    }
    
    0 讨论(0)
  • 2021-01-16 23:37

    Your return statement should be outside the for loop. It only executes the first loop then bails out.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-16 23:37

    This is how I attempted to solve it:

    function LongestWord(sen) { 
        var wordArray = sen.match(/\w+/gi);
        var longest = 0; 
        var word = undefined; 
      for(var i = 0; i < wordArray.length; i++){
        if(wordArray[i].length > longest){
          word = wordArray[i];
          longest = word.length;
        }
      }
      return word;      
    }
    
    0 讨论(0)
  • 2021-01-16 23:37

    Try using the following code sample:

    function findLongestWord(str){
      var arr=[];
      arr=str.split(' ');
      arr=arr.sort(function(a,b){
        return b.length-a.length;
      });
      var st=arr[0];
      return st.length;
    }
    
    findLongestWord("The quick brown fox jumped over the lazy dog");
    
    0 讨论(0)
  • 2021-01-16 23:40

    Your return statement is misplaced, put it after the loop :

    function findLongestWord(str) {
    
       var words = str.split(' ');
       var longest = 0;
    
       for (var i=0;i<words.length;i++) {
            if (words[i].length > longest) {
                 longest = words[i].length;
            }  
       }
    
       return longest;
    }
    
    0 讨论(0)
提交回复
热议问题