Javascript: find longest word in a string

Go To StackoverFlow.com

12

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.

2013-06-30 03:12
by bard
don't name an array of strings straaronman 2013-06-30 03:18


16

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++)
2013-06-30 03:17
by Musa
Thanks! The second solution is what I was trying to do, but I missed out the equal sign - bard 2013-06-30 03:26
I would personally recommend the first solution for readability to others. The second one takes longer to write and would be less efficient if not for compiler optimizations (recalculating str.length-1 each time, but compilers don't do dumb things like that these days) so real world code would not use the second solution, in my experience - coder543 2013-06-30 04:17
@coder543, it must recompute each iteration because .length could be an accessor that changes. It's a fast operation though - zzzzBov 2015-03-26 17:55
Mathematically, the the two are equivalent. i < x is the same as i <= x - 1, so a compiler could optimize that if it has an optimization pass for it - coder543 2015-03-27 19:09


9

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

function longer(champ, contender) {
  return (contender.length > champ.length) ? contender: champ;
}

function longestWord(str) {
    var words = str.split(' ');
    return words.reduce(longer);
}

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

2013-06-30 03:47
by merv


4

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/

2013-06-30 03:15
by tymeJV


4

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

2013-06-30 03:27
by aaronman


3

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.

2013-06-30 03:15
by acdcjunior


1

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++)
2013-06-30 03:19
by Raj Nathani


1

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; });
}
2014-06-03 13:06
by Gergo Erdosi


1

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
2014-11-08 10:07
by Shushanth Pallegar


1

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"));
2017-02-07 23:47
by NoName


1

function longestWord(sent){
 var arr = sent.match(/[a-z]+/gi);
 arr.sort(function(a, b){
 return b.length - a.length;
});
 return arr[0];
}
longestWord('hello man@#$%');
// ==> output: hello
2017-06-01 21:45
by bekzat


1

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; 
}
2017-06-27 21:36
by Cheyenne Crawford


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.

2013-06-30 03:15
by Zong
am I losing my mind or are these two identica - aaronman 2013-06-30 03:27
@aaronman LOL. Since the answer's been accepted I won't edit it. : - Zong 2013-06-30 04:06


0

You need to use:

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

That way it will scan the entire phrase

2013-06-30 03:21
by Dylan Vander Berg


0

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;
}
2013-06-30 14:30
by bard


0

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;

}

2013-12-05 18:54
by Matt.Talbot


0

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
};
2015-03-26 17:50
by user3815014


0

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;
}
2015-08-05 16:52
by Antares


0

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 b-a;
     });   
   }
  return result[0];
}

2016-07-16 23:13
by PKA


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];
}
2017-04-05 10:45
by fidel m.


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;
    }
2017-11-24 21:33
by John Kahenya
Same answer already given and accepted - matthias 2017-11-24 21:54


0

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 ')
2018-03-21 23:16
by Aysun
While this might be a viable solution a sort might take much longer than one iteration over an array - Kami Kaze 2018-03-21 23:40


0

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>

2018-05-04 09:05
by Alok Ranjan


0

    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");
2018-07-02 08:08
by ganesh kalje


0

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.

2018-10-17 10:23
by Babak Habibi


-1

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;
}
2017-11-18 21:53
by Gatha Sehgal
This answers an old question (2013) when there is an already accepted answer which states the same thing as you have - Sebastian 2017-11-18 22:11


-1

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 ')
2018-03-21 23:01
by Aysun
this suffers of the same problem as the question. This is no challenge to give all possible to solutions to a problem but to help OP with his wrong code - Kami Kaze 2018-03-21 23:43