Find the longest word in a string?

前端 未结 8 2152
旧巷少年郎
旧巷少年郎 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 06:06

    When you use words.push(str.split(" ")), the array words looks like

    [
        ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
    ]
    

    Another problem is that when you check longest[0].length for the first iteration in the for, it is undefined. Which results in the error

    Uncaught TypeError: Cannot read property 'length' of undefined

    To solve this, you can use longest as string instead of array. And in the for, assign the string having the length greater than the current longest string to it.

    At the end of the function, you can return the longest string.

    Problems/Suggestions:

    1. Use str.split(' ') to directly assignment to words variable
    2. Use longest as string variable instead of array and initialize it to empty string, i.e. '', to avoid the above error
    3. Compare the length of the longest with the string in the words array
    4. If the length of the string in words array is greater than the longest, update the longest.
    5. Use \s+ to split the string by spaces

    function findLongestWord(str) {
      var words = str.split(/\s+/);
      var longest = '';
    
      for (var i = 0; i < words.length; i++) {
        if (words[i].length > longest.length) {
          longest = words[i];
        }
      }
      return longest;
    }
    
    var longestWord = findLongestWord('The quick brown fox jumped over the lazy dog');
    
    document.write('Longest Word: "' + longestWord + '"');
    document.write('<br />Longest Word Length: ' + longestWord.length);

    0 讨论(0)
  • 2021-01-17 06:06
      if (words[i].length > longest[0].length)
    

    You will be getting error in above line. As at first time, it is empty.

    0 讨论(0)
提交回复
热议问题