Find the longest word in a string?

前端 未结 8 2315
旧巷少年郎
旧巷少年郎 2021-01-17 05:34

I am trying to write a basic javascript function to find the longest word in a string and log it\'s length.

So far I have:

function findLongestWord(         


        
8条回答
  •  清歌不尽
    2021-01-17 05:44

    Here is another shorter version:

    function findTheLongestWord(str) {
      var temp = '';
      (str || "").split(/\s+/).forEach(function(word) {
        temp = word.length > temp.length && word || temp;
      });
      return "longest word is: " + temp + " and it's length is: " + temp.length;
    }
    
    alert (findTheLongestWord("The quick brown fox jumped over the lazy dog, once again!"));

提交回复
热议问题