简体   繁体   中英

Find out the longest word from a sentence - Javascript

Is there any way to find out the longest word in Javascript? It should ignore punctuation marks too!

I understood the logic, but the code... sigh

Here's what we do -

  1. Count the number of alphanumeric characters that are together, not separated by a space or any sign.

  2. Get their lengths.

  3. Find the biggest length in all.
  4. Return the word with the biggest length.

Hope I'm making myself clear...

Split the string, loop over the parts and keep track of the longest one.

Something like this:

var parts = sentence.split();
var longestIndex = -1;
var longestWord = 0;

for(var i=0; i < parts.length; i++){
    if(parts[i].length > longestWord){
        longestWord = parts[i].length;
        longestIndex = i;
    }
}

alert("longest word is " + parts[longestIndex] + ": " + longestWord + " characters");

If you need to split on non alphabetic characters as well as spaces you need to use regexes. You can change this line:

var parts = sentence.split();

To this (thanks Kooilnc for the regex):

var parts = sentence.match(/\w[a-z]{0,}/gi);

Working jsfiddle

var longest_word = arr.reduce(function (x, y) { return x.length > y.length ? x : y; });

There you go.

Using it:

var arr = [ 'lol', 'loll', 'lollll', 'lo', 'l' ];
var longest_word = arr.reduce(function (x, y) { return x.length > y.length ? x : y; });

So turn your sentence into an array, then the variable longest_word will be the longest word in that array.

try this:

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

You can split a string to an array of words only (no sepators, digits etc) using the match method, and sort that descending on length of each element, after which element 0 is the longest word.

It could be a String.prototype extension

String.prototype.longestWord = function(){
  return (this.match(/\w[a-z]{0,}/gi) || [''])
          .sort(function(a,b){return b.length-a.length;})[0];
}
//usage
'We saw it ...! A lazy cat walking - or did we?'.longestWord(); //=> walking
'------------'.longestWord();                                   //=> ''
'---aa--b----'.longestWord();                                   //=> 'aa'

The same as a function, using Array.reduce

function longestWord(str){
   return (str.match(/\w[a-z]{0,}/gi) || [''])
           .reduce( function(a,b){return a.length>b.length ? a : b;} );
}

Fiddle here

This is how I attempted to solve the problem:

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; 

}

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