Find the longest word in a string using javascript

后端 未结 10 1249
长情又很酷
长情又很酷 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条回答
  •  刺人心
    刺人心 (楼主)
    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;      
    }
    

提交回复
热议问题