Find the Longest Word in a String - JavaScript Solution & Walkthrough

(04/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Find the Longest Word in a String - JavaScript Solution & Walkthrough

04/16 Find the Longest Word in a String

Return the length of the longest word in the provided sentence.

Your response should be a number.

function findLongestWordLength(str) {

  return str.length;
}

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

Credit: FreeCodeCamp.org

Understanding the Challenge

So here we have another straightforward challenge. You will be given a string. Your task is to create a function that returns the length of the longest word in the given string(or sentence).

For example, if you are given the string "She is going to school". Your function should return the number 6. This is because the longest word in that string is the word "school". And the length of the word school is 6. Remember, the challenge says your response (or what your function returns) should be a number.

Okay, now let's go ahead with our pseudocode.

Pseudocode

Given a string (or sentence)
  convert the string into an array of the words that forms the sentence
  Find the length of each word in that array
Return the length that is the highest

Solving the Challenge

First, we need to convert the given sentence into an array. This will help us to get the individual words that forms the sentence. We can do that by using the .split() Let's call the array strArray.

const strArray = str.split(" ")
console.log(strArray) 
// [ 'The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog' ]

We call the .split(" ") method with space (" ") as an argument. Note, this argument is space and not an empty string ("")

Okay, so now that we have an array of the words that forms the given sentence, we can use the .map() to find the length of each word

const lengthArray = strArray.map(word => word.length);
console.log(lengthArray) // [ 3, 5, 5, 3, 6, 4, 3, 4, 3 ]

So we get the length of each word. For example, the first is "The" which has a length of 3, the second word is "quick" with a length of 5, etc.

The next thing to do is to get the highest number in lengthArray. To do that, we can use Math.max()

const longestWordLength = Math.max(...lengthArray)
console.log(longestWordLength) // 6

Note: We use the ... spread operator which helps us to get the items in the array.

Finally, we return longestWordLength and our function is complete!

return longestWordLength;

Final Solution

function findLongestWordLength(str) {
  const strArray = str.split(" ");
  const lengthArray = strArray.map(word => word.length);
  const longestWordLength = Math.max(...lengthArray);

  return longestWordLength
}

findLongestWordLength("The quick brown fox jumped over the lazy dog"); // 6

Congratulations!

You just cracked the fourth challenge in this series.

Cheers and happy coding!