# Find the Longest Word in a String

## Problem Explanation

You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.

## Hints

### Hint 1

You could iterate through each letter of the string using a `for...of` loop.

### Hint 2

You will need to figure out a way to keep track globally of the greatest current length.

### Hint 3

Remember how to get the length of elements on the array? `Array[index].length`.

## Solutions

Solution 1 (Click to Show/Hide)
``````function findLongestWordLength(str) {
let record = 0;
let i = 0;
let wordLength = 0;
while(true) {
wordLength = str.indexOf(' ', i) - (i);
if (str.indexOf(' ', i) === -1) {
wordLength = str.length-i;
}
i = i + (wordLength > 0 ? wordLength : wordLength*(-1)) + 1;
// OR...
// i += Math.abs(wordLength)+1;
if (wordLength > record) {
record = wordLength;
}
if (i > str.length) {
break;
}
}
return record;
}
``````

### Code Explanation

The string is indexed into using the variable `i`, whilst `i` is less than the length of the string. The index of each space is found within the string, and this is used as the length of each word.

Solution 2 (Click to Show/Hide)
``````function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;

for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}

return maxLength;
}
``````

#### Code Explanation

Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.

Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.

Solution 3 (Click to Show/Hide)

Using `.reduce()`

``````function findLongestWordLength(s) {
return s.split(' ')
.reduce(function(x, y) {
return Math.max(x, y.length)
}, 0);
}
``````

#### Code Explanation

For more information on `reduce` click here.

In case youâ€™re wondering about that `0` after the callback function, it is used to give an initial value to the `x`, so that `Math.max` will know where to start.

Solution 4 (Click to Show/Hide)

Using `.map()`

``````function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
``````

#### Code Explanation

We provide `Math.max` with the length of each word as argument, and it will simply return the highest of all.

Letâ€™s analyze everything inside the `Math.max` parenthesees to understand how we do that.

`str.split(" ")` splits the string into an array, taking spaces as separators. It returns this array: [â€śTheâ€ť,"quick,â€śbrownâ€ť,â€śfoxâ€ť,â€śjumpedâ€ť,â€śoverâ€ť,â€śtheâ€ť,â€ślazyâ€ť,â€śdogâ€ť].

Then, we will make another array, made from the lengths of each element of the `str.split(" ")` array with `map()`.

`str.split(" ").map(word => word.length)` returns [3, 5, 5, 3, 6, 4, 3, 4, 3]

Finally, we pass the array as argument for the Math.max function with the spread operator `...`

For more information on `map` click here.

Solution 5 (Click to Show/Hide)

Using recursion

``````function findLongestWordLength(str) {
//split the string into individual words
//(important!!, you'll see why later)
str = str.split(" ");

//str only has 1 element left that is the longest element,
//return the length of that element
if (str.length == 1) {
return str[0].length;
}

//if the first element's length is greater than the second element's (or equal)
//remove the second element and recursively call the function)
if (str[0].length >= str[1].length) {
str.splice(1, 1);
return findLongestWordLength(str.join(" "));
}

//if the second element's length is greater thant the first element's start
//call the function past the first element
if (str[0].length <= str[1].length) {
// from the first element to the last element inclusive.
return findLongestWordLength(str.slice(1, str.length).join(" "));
}
}
``````

#### Code Explanation

The first line splits the string into individual words. Then we check if `str` only has 1 element left then that is the longest element and we return it. If the first elementâ€™s length is greater than the second elementâ€™s (or equal), we remove the second element and recursively call the function `findLongestWord`. However, if the second elementâ€™s length is greater thant the first elementâ€™s start, then we call the function past the first element.

44 Likes

The `JS Math Max` link in the intermediate function explanations returns-

{â€śerrorsâ€ť:[â€śThe requested URL or resource could not be found.â€ť],â€śerror_typeâ€ť:â€śnot_foundâ€ť}

It might just be to MDN anyway, but I didnâ€™t know if it was a special FCC article.

First ,when i use split(), I found str1 is a list, so , I just think why not get a list which contain every wordâ€™s length.
So I get a list of number, next problem is found the max number of the list, just google js max, so i get the solution.
I have compare my solution with official, my solution is not perfect ,but itâ€™s a another way.
I feel happy with that.

`function findLongestWord(str) {
var str1 = str.split(" ");
var list = [];
for (i=0;i<str1.length;i++) {
list.push(str1[i].length) ;
}
return Math.max.apply(null ,list);
}

findLongestWord(â€śThe quick brown fox jumped over the lazy dogâ€ť);`

8 Likes
``````function findLongestWord(str) {
``````

return str.split(â€™ ').map(function(val){
return val.length;
}).sort(function(a, b){
return b - a;
})[0];

}

findLongestWord(â€śThe quick brown fox jumped over the lazy dogâ€ť);

8 Likes

This is my solution:

``````function findLongestWord(str) {

var arr = str.split(" ");//split sentence to an array
var longestWord = arr[0];//assume longest word is the first word of an array
for (var i=0; i< arr.length; i++){ //iterate through array of words

if(arr[i].length > longestWord.length){
//compare other words of an array if they are longer than the first one
longestWord = arr[i];
}
}
return longestWord.length;//return length of the longest word

}
//test
findLongestWord("What if we try a super-long word such as otorhinolaryngology");``````
11 Likes

Here is my take on a solution.

``````function findLongestWord(str) {
return Math.max.apply(Math, str.split(' ').map(val = val => val.length));
}
``````

``````function findLongestWord(str) {
return Math.max(...str.split(' ').map((word) => word.length));
}

``````

7 Likes

Hi! I wanted to contribute with my solution

``````function findLongestWord(str) {

// Split the string into an array
var array = str.split(" ");

// Then sort the array by its elements length, from longest to shortest
array.sort(function(a,b) {
return b.length - a.length;
});

// Since the first element of the array will be the longest, then return the length of the first element
return array[0].length;
}

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

Hi , i did it w/ sort function;

``````function findLongestWord(str) {
var abc = str.split(" ");
var newStr = [];
for (var i = 0; i < abc.length; i++) {

newStr.push(abc[i].length);
}
}

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

``````
5 Likes

Very short code; how you managed to simply write var longestWord in a such way in if condition ; Appreciate Really!! your logic;

``````      function findLongestWord(str) {

var arr = str.split(" ");//split sentence to an array
var longestWord = arr[0];//assume longest word is the first word of an array
for (var i=0; i< arr.length; i++){ //iterate through array of words

if(arr[i].length > longestWord.length){
//compare other words of an array if they are longer than the first one
console.log(longestWord = arr[i]);
}
}
return //console.log(longestWord.length);//return length of the longest word

}
//test
findLongestWord("What if we try a super-long word such as otorhinolaryngology");
``````

`
examining your code, where I have written console log in gives two strings, while should give just a lonestWord; Why could you explain me plz

1 Like

What is the advantage of the Advanced/ Intermediate Code over the Basic?

4 Likes

Hi there! This is my solution.

``````function findLongestWord(str) {
return str.split(" ").sort(function(a,b){
return b.length - a.length;
})[0].length;
}

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

11 Likes

Here is my take:slight_smile:

function findLongestWord(str) {
// Split the string into an array
var array = str.split(" ");
var lengths = array.map(function(word){
return word.length
})
var q = Math.max.apply(null, lengths);

return q

}`

2 Likes

I really like the solutions using .reduce but I was wondering whether it is noticeably faster than the Basic Code Solution.

function findLongestWord(str) {

var word = str.split(â€™ ');
var x = word[0].length;

for(i=0; i<word.length; i++){
if(word[i].length>x){
x = word[i].length;
}
}

return x;
}

findLongestWord(â€śThe quick brown fox jumped over the lazy dogâ€ť);

My solution here i used the .toLowerCase() so when sorted, it would not put the capital string first but any comments on my solution would help thanks.

function findLongestWord(str) {
var strArry=[];

strArry=str.toLowerCase().split(â€™ ');
strArry.sort(function(a,b){
return b.length-a.length;
});

return strArry[0].length;
}

findLongestWord(â€śWhat if we try a super-long word such as otorhinolaryngologyâ€ť);

2 Likes

I managed to reach the basic solution, and looking at the hints am trying to do the advanced solution, but am encountering a â€śType Error: str.splice is not a functionâ€ť error message that for the life of me I canâ€™t figure out. Can anyone explain my mistake? Code is below, but I also had an question about the intermediate solution:

function findLongestWord(str) {

if (!str.isArray) {
str.split(" ");}

if (str.length == 1) {
return str[0];
}

if (str[0].length >= str[1].length) {
str.splice(1,1);
return findLongestWord(str);
}

if (str[0].length <= str[1].length) {
str.splice(0,1);
return findLongestWord(str);
}

}
findLongestWord(â€śThe quick brown fox jumped over the lazy dogâ€ť);

Regarding the intermediate solution, can someone please explain the logic behind function(x, y) {
return Math.max(x, y.length)
}

Thanks

Hi @Alais29,

I did the exact same thing .

Why doesnâ€™t this work?

``````var array = [];
function findLongestWord(str) {
var newArray = str.split(" ");

for (i = 0; i < newArray.length; i++) {
var newLength = newArray[i].length;
array = array.concat(newLength);

}
return array.reduce(function(previousValue, currentValue){
return Math.max(previousValue,currentValue);
});

}

findLongestWord("May the force be with you");``````