Use JavaScript to find the longest word in a sentence and return its length (three methods)

Source: Internet
Author: User



1. Use the Sort sorting method (the dumbest one I can remember)


Function findLongestWord(str) {

   Var strArr = str.split(" ");
  / / Save the length of the string, save an array
   Var lenArr = strArr.map(function(item){
     Return item.length;
   });
     Var lastArr = lenArr.sort(function(a,b){
        Return b-a;
     });
  Var num = lastArr[0];
   
   Return num;
}
 

findLongestWord("The quick brown fox jumped over the lazy dog"); 


2. Using the Math.max () method
Since the max () function can only receive numbers as arguments, here flattering uses the Apply () API to receive the attributes of the array as parameters.
Ref: 53013370


Function findLongestWord(str) {

   Var strArr = str.split(" ");
  / / Save the length of the string, save an array
   Var lenArr = strArr.map(function(item){
     Return item.length;
   });
     Var num = Math.max.apply(null, lenArr);
  
   Return num;
}
 


findLongestWord("The quick brown fox jumped over the lazy dog"); 


3. Ways to store using temporary variables
Reference Blog: 68948891


 
function findLongestWord(str) { var arr = str.split(" "); var max = 0; var temp; for(var i = 0;i <arr.length;i++){
    temp = arr[i].length; if(temp>max){
      max = temp;
    }
  } return max;
}

findLongestWord("Google do a ");



Use JavaScript to find the longest word in a sentence and return its length (three methods)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.