Find the longest word in a string using javascript

后端 未结 10 1160
长情又很酷
长情又很酷 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:45

    I would do something like this:

    function longestWord(str){
      return str.match(/\w+/g).reduce((p,c) => p.length > c.length ? p.length:c.length);
    }
    
    0 讨论(0)
  • 2021-01-16 23:49
    function findLongestWord(str) {
      //This is what I  used to find how many characters were in the largest word
      return str
              .replace(/[^\w ]/g,'')                            
              .split(' ')                                       
              .sort(function(a, b) {return a.length-b.length;}) 
              .pop().length;                                           
    
    }
    findLongestWord('The quick brown fox jumped over the lazy dog');
    
    0 讨论(0)
  • 2021-01-16 23:53

    Your return statement is in the wrong place, as mccainz said, however you should also be saving the word if you want to return the actual word.

    function findLongestWord(str) {
      var words = str.split(' ');
      var longestLength = 0;
      var longestWord;
      for (var i=0;i<words.length;i++) {
        if (words[i].length > longestLength) {
           longestLength = words[i].length;
           longestWord = words[i];
        }
      }
      return longestWord;
    }
    
    0 讨论(0)
  • 2021-01-16 23:53

    Here's a functional approach:

    function findLongestWord(str) {
      return str
              .replace(/[^\w ]/g,'')                            //remove punctuation
              .split(' ')                                       //create array
              .sort(function(a, b) {return a.length-b.length;}) //sort in order of word length
              .pop();                                           //pop the last element
    }
    
    console.log(findLongestWord('For the next 60s, we will be conducting a test.')); //conducting

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