简体   繁体   中英

Find the longest word in a string using javascript

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 findLongestWord(str) {
  var words = str.split(' ');
  var longest = 0;

  for (var i=0;i<words.length;i++) {
    if (words[i].length > longest) {
      longest = words[i].length;
    }

    return longest;
  }
}

Your return statement should be outside the for loop. It only executes the first loop then bails out.

Here is how I did it (I enclose a commented long version and a uncommented short version):

 /***************
 * LONG VERSION *
 ***************/
function findLongestWord(str) {
  // Create an array out of the string
  var arr = str.split(' ');

  // Sort the array from shortest to largest string
  arr = arr.sort(function(a, b) {
    return a.length-b.length;
  });
  // The longest string is now at the end of the array

  // Get the length of the longest string in the Array
  var longestString = arr.pop().length;

  // return the lenght of the longest string
  return longestString;
}

/*****************
 * SHORT VERSION *
 ****************/
function findLongestWord(str) {
  return str
    .split(' ')
    .sort(function(a, b) { return a.length-b.length; }) 
    .pop().length;
}

Your return statement is misplaced, put it after the loop :

function findLongestWord(str) {

   var words = str.split(' ');
   var longest = 0;

   for (var i=0;i<words.length;i++) {
        if (words[i].length > longest) {
             longest = words[i].length;
        }  
   }

   return longest;
}

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;
}

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

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);
}

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;      
}
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');

here is how I did it.

function findLongestWord(str) {
  var strArray =[];
  var numArray=[];
  var sortedNumArray=[];

  strArray = str.split(" ");

  numArray = strArray.map(function(val){return val.length;});

  sortedNumArray=numArray.sort(function(a,b){return a-b;});

  return sortedNumArray.pop();

}

Try using the following code sample:

function findLongestWord(str){
  var arr=[];
  arr=str.split(' ');
  arr=arr.sort(function(a,b){
    return b.length-a.length;
  });
  var st=arr[0];
  return st.length;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM