3

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

Namanyay Goel
  • 2,641
  • 3
  • 20
  • 26

5 Answers5

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

Asciiom
  • 9,867
  • 7
  • 38
  • 57
  • I need the code, I'm pretty sure I understood the logic. I'm such a noob that I don't even know how to split the strings. – Namanyay Goel Aug 31 '12 at 13:54
  • @Namanyayg are you sure of "noob" thing? your personal site says "I Design Amazing Websites and themes!" :-) – Aman J Aug 31 '12 at 13:58
  • 1
    _Design_, not _develop_. Big difference. – Ashley Strout Aug 31 '12 at 13:59
  • JS isn't required to design 'amazing websites and themes' :P I do client-side JS okay-ish ( I don't use it much, just for editing JQ plugins) and am thinking of brushing up programming JS. – Namanyay Goel Aug 31 '12 at 13:59
  • for (i in parts) is NOT the way to loop over an array – hvgotcodes Aug 31 '12 at 14:01
  • @hvgotcodes why not, it works fine. It's not a jQuery question. http://www.w3schools.com/js/js_loop_for_in.asp – Asciiom Aug 31 '12 at 14:03
  • yeah in that very link, it says for/in loops over **properties in an object** not indexes in the array. Print out `i` for each iteration in the loop. – hvgotcodes Aug 31 '12 at 14:09
  • It's untested code, I thought I used it like that before. In any case, I updated the code to use a conventional for loop, that way it should work without question. – Asciiom Aug 31 '12 at 14:12
  • @Namanyayg I updated my answer to split the sentence based on spaces and no alphabetic characters. I provided a working jsfiddle. – Asciiom Aug 31 '12 at 14:24
  • 1
    @Jeroen: you could've mentioned the origin of the regular expression, right? – KooiInc Aug 31 '12 at 14:32
  • @Kooilnc sorry, of course :) An upvote for my gratitude/respect – Asciiom Aug 31 '12 at 14:34
  • @Jeroen I didnt say it wouldn't work; I said it wasn't correct. Check this out http://jsfiddle.net/pQa6N/2/. – hvgotcodes Aug 31 '12 at 14:35
  • I've been using it like that for a while now, cross browser, no problems. Why isn't it correct? – Asciiom Aug 31 '12 at 14:37
  • @hvgotcodes: you are mixing Object looping with Array looping. Therefore it is your code @ jsfiddle.net/pQa6N/2 that is not correct. – KooiInc Aug 31 '12 at 15:02
  • @KooiInc originally he was looping over the array with a for/in. Your point is my point. My code is intentionally broken to show the error... – hvgotcodes Aug 31 '12 at 15:06
  • 1
    @hvgotcodes: ok, missed that version, sorry. @Jeroen: don't use `for ... in` on Arrays, it may give unpredictable results. See http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays – KooiInc Aug 31 '12 at 15:12
8
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.

Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
4

try this:

sentence_array = sentence.split(' ');
var longest = sentence_array.sort(function (a, b) { return b.length - a.length; })[0];
Shreedhar
  • 5,502
  • 3
  • 22
  • 27
2

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

KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

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; 

}
user201827
  • 21
  • 1