简体   繁体   中英

Javascript: find longest word in a string

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}

When I call longestWord("Pride and Prejudice") , it returns 'Pride' and not 'Prejudice' which is the longest word... why? I checked some other similar questions, but the solutions looked a lot like my code.

That's because you're not comparing all the items in the array, you leave out the last one.

for (var i = 0; i < str.length - 1; i++)

should be

for (var i = 0; i < str.length; i++)

or

for (var i = 0; i <= str.length - 1; i++)

One advantage to taking a functional approach to such problems is that you don't even have to keep count

See MDN Array.reduce for more info. (note: reduce needs shim for IE8)

 function longer(champ, contender) { return (contender.length > champ.length) ? contender : champ; } function longestWord(str) { var words = str.split(' '); return words.reduce(longer); } console.log(longestWord("The quick brown fox jumped over the lazy dogs"));

Here this is your solution with a forEach, this will help you avoid the error in the future

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    return word;
}
console.log(longestWord("pride and prejudice"));

Your original problem was just the str.length - 1 should have just been str.length , originally you wouldn't have gotten to the last element of the array

You have a -1 in your condition, it never even scans it:

for (var i = 0; i < str.length - 1; i++) {

Should be:

for (var i = 0; i < str.length; i++) {

Demo: http://jsfiddle.net/LfgFk/

The index is going up to str.length -1 :

for (var i = 0; i < str.length - 1; i++) {

So the last word is not processed .

Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice") . You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA ).

In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.

for (var i = 0; i < str.length; i++) {

Check a demo with both versions (the problematic and the fixed): link here .

You can simplify your code with a library like Lo-Dash :

function longestWord(string) {
    var words = string.split(' ');
    return _.max(words, function(word) { return word.length; });
}

ForEach is faster in FF but slower in Chrome, but for loop with the cached length and function apply/call is quite faster in both FF and chrome.

Hope the below code helps:

function getLongest (arrStr) {
  var longest = 0, word;

  for(var i=0 , len = arrStr.length ; i < len ; i++){

    if(longest < arrStr[i].length) {
       longest = arrStr[i].length;
       word = arrStr[i];
    }

  }

  return word;
}

function isLongest (str) {
  var arrayStr = str.split(' ');
  return function(fn) {
    return fn.apply(this,[arrayStr]);
  }
}

isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
for (var i = 0; i < str.length - 1; i++)

to

for (var i = 0; i <= str.length - 1; i++)

OR

for (var i = 0; i < str.length; i++)

does this solve the problem??

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i <= str.length - 1; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}

document.write(longestWord("pride and prejudice"));
function longestWord(sentence){
 var arr = sentence.match(/[a-z]+/gi);
 arr.sort(function(a, b){
 return b.length - a.length;
});
 return arr[0];
}
longestWord('hello man@#$%');
// ==> output: hello

I find that the .map method here helps a lot (this is if you want the character count of the word, not the word itself):

 function findLongestWord(str) {   
   var array = str.split(/\s+/);
   var wordLength = array.map(function(i) {
     return i.length;                       
   });   
   var largest = Math.max.apply(Math, wordLength);   
   return largest; 
}
function LongestWord(sen) { 

  // code goes here  
  const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
  wordsArray.sort((a, b) => a.length < b.length);
  return wordsArray[0]; 

}

Is there a specific reason

for (var i = 0; i < str.length - 1; i++)

isn't

for (var i = 0; i < str.length - 1; i++)

That seems like it could be the cause.

You need to use:

for (var i=0;i<=str.length - 1; i++)

That way it will scan the entire phrase

Thanks everyone, this is the fixed code:

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length; i++) {
        var checkedLetters = "";
        for (var j = 0; j < str[i].length; j++) {
            if (/[a-zA-Z]/.test(str[i][j])) {
                checkedLetters += str[i][j];
            }
        if (longest < checkedLetters.length) {
            longest = checkedLetters.length;
            word = checkedLetters;
            }
        }
    }
    return word;
}

This seems to be the easiest way to do this.

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;

    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });

return word;

}

I would say using the forEach loop is the most understandable version

function longestWord(sen) {
  big_word = ""
  words = sen.split(" ")
  words.forEach(function(word){
    if (word.length > big_word.length){
        big_word = word
    };
  });
return big_word
};

I think this is more easy

function findLongestWord(str) {
    var longestStr = 0;
    for (var x=0;x<str.split(' ').length;x++){
        if (longestStr < str.split(' ')[x].length){
            longestStr = str.split(' ')[x].length;
        }
    }
    return longestStr;
}

Here is one other way to solve it.

 function findLongestWord(str) { var result = []; var one = str.split(" "); for (var i = 0; i < one.length; i++) { result[i] = one[i].length; result.reverse().sort(function(a,b) { return ba; }); } return result[0]; }

Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.

function longest(string){
    var longestWord = string.split(' ').sort(function(a,b){
        return b.length - a.length;
    });
    return longestWord[0];
}

TRY THIS

 function longest(string) {
        var str = string.split(" ");
        var longest = 0;
        var word = null;
        for (var i = 0; i <= str.length - 1; i++) {
            if (longest < str[i].length) {
                longest = str[i].length;
                word = str[i];
            }
        }
        return word;
    }

Another method is by using sort:

    function longestWord(string) {
        let longest = 0;
        let str = str.split(" ").sort((word1,word2)=>{
        });
        return str[0].length;
   }
   longestWord('I love Python ')

Code below will find the largest word and its length from a string. Code is in plain JavaScript and html.

 function findLongestWord() { var str = document.getElementById('inputText').value; calculateLength(str); } function calculateLength(str) { var substring = str.split(" "); var minChar = ''; for (var i = 0; i <= substring.length - 1; i++) { if (substring[i].length >= minChar.length) { minChar = substring[i]; } } document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar; document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length; }
 <!doctype html> <html lang="en"> <head> </head> <body> <input type="text" id="inputText"> <br/> <button onclick=findLongestWord()>Click to find longest word</button> <br/> <div id="longChar"></div> <br/> <div id="longCharLength"></div> </body> <script src="longestWord.js"></script> </html>

    function findLongestWord(str) {
       let stringArray = str.split(" ");
       stringArray.sort(function(a, b){
          return a.split('').length < b.split('').length;
       })
       return stringArray[0];
    }

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

I will refer you to this awesome article which defines three ways:

1 - Find the Longest Word With a FOR Loop

    function findLongestWord(str) {
  var strSplit = str.split(' ');
  var longestWord = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWord){
    longestWord = strSplit[i].length;
     }
  }
  return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2 - Find the Longest Word With the sort() Method

function findLongestWord(str) {
  var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
  return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

3 - Find the Longest Word With the reduce() Method

function findLongestWord(str) {
  var longestWord = str.split(' ').reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, "");
  return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

Of course, it returns the length of the biggest word if you want to get the string, just get rid of the length in return part.

Solutions above are incomplete. What if there r 2 or more words that have same length. here is a better solution:

longest = str => {
  let words = str.split(" ");
  let size = 0;
  let max = [""];

  for (let i = 0; i < words.length; i++) {
    if (words[i].length > size) {
      size = words[i].length;
    }
    if (max[max.length - 1].length < words[i].length) {
      max = [];
      max.push(words[i]);
    } else {
      max = [...max, words[i]];
    }
  }
  return max;
};

 function sortNumber(a, b) { return a - b; } function findLongestWordLength(str) { var split = str.split(" "); var arr=[]; for(var i=0;i<split.length;i++){ arr.push(split[i].length); } arr.sort(sortNumber); console.log(arr[arr.length-1]); return(arr[arr.length-1]); } findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

 const longestWord = string => { stringArray = string.split(' ').sort( (a,b) => b.length - a.length) let longestArray= stringArray.filter( word => word.length === stringArray[0].length ) if(longestArray.length === 1){ console.log(longestArray[0]) } else { console.log(longestArray) } } longestWord("Pride and Prejudice")

// My simple solution.

const findLongestWordLength = str => {
    let array = str.split(" ");
    let longest = 0;

    array.map(e => {
        if (e.length > longest) {
            longest = e.length;
        }
    })
    return longest;
}

Check if this helps:

function longestWord(string){
  var str = string.split(" ");
  var longest = 0;
  var word = null;
  for(var i=0; i < str.length; i++){
    if(longest < str[i].length){
      longest=str[i].length;
      word=str[i];
    }
  }
  return word;
}
function longestWord(string) {
   var str = string.split(" ");
   var longest = 0;
   var word = null;
   for (var i=0; i < str.length-1; i++) {
      word = longest < str[i].length ? str[i].length : longest;
         word = str[i];
   }
   return word;
   }
   longestWord('I love Python ')

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