Find the longest word in a string?

前端 未结 8 2305
旧巷少年郎
旧巷少年郎 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条回答
  •  猫巷女王i
    2021-01-17 06:00

    You can greatly simplify this using Array.prototype.sort and Array.prototype.shift. For example

    var str = 'The quick brown fox jumped over the lazy dog',
        longest = str.split(' ').sort(function(a, b) {
                      return b.length - a.length;
                  }).shift();
    
    document.getElementById('word').innerHTML = longest;
    document.getElementById('length').innerHTML = longest.length;


    The sort() will produce an array of strings sorted by their length (longest to shortest) and shift() grabs the first element. You could also sort the other way (shortest to longest) using return a.length - b.length and pop() instead of shift() to grab the last element.

提交回复
热议问题