最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Find out the longest word from a sentence - Javascript - Stack Overflow

programmeradmin1浏览0评论

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...

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...

Share Improve this question asked Aug 31, 2012 at 13:51 Namanyay GoelNamanyay Goel 2,6603 gold badges21 silver badges26 bronze badges 4
  • 1 Code?? u must tried something. – Aman J Commented Aug 31, 2012 at 13:54
  • @hvgotcodes no, just a challenge I found on Coderbyte – Namanyay Goel Commented Aug 31, 2012 at 14:00
  • @Namanyayg haha, it's not supposed to be 'find someone else to do the challenge' ;) – Ryan McDonough Commented Aug 31, 2012 at 14:03
  • @RyanMcDonough I came here after I could find no solution to it. I usually search a lot and figure out a solution on my own, but here, I didn't even knew where to start. – Namanyay Goel Commented Aug 31, 2012 at 14:05
Add a comment  | 

5 Answers 5

Reset to default 9

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; 

}
发布评论

评论列表(0)

  1. 暂无评论