Longest Word in String

This blog explains my solution to Find the Longest Word in a String, a Bonfire exercise from Free Code Camp. The goal of this exercise is to find the longest word in a string and return its length as a number. To write the code, you need to split a phrase into an array of words, and iterate through index until you find the word with the longest length. This is done using the split() method and string.length property.

This tutorial is written for people who know a little about JavaScript but are not familiar with the split() method and string.length property. You might be new to JavaScript or just curious about how this method and property work.

Initial Problem

The initial code that’s given looks like this:

Solution

In your quest to find the longest word, you should begin by splitting the string into an array of words. This is done by creating an object, which in this case is called “words”. Then set this new object equal to the string to which you apply the split() method.

As you may know, the split() method returns a new array. In order to include a blank space between words, you should specify the separator parameter in the following way: split(“ “). If the separator is not identified or left blank, by default, the array that’s generated contains the entire string.

Next we need to iterate through the index to find the length of each word. This is achieved by created a for loop. But it’s necessary to create a variable, called I called “longestLength” - this is used to globally track the word with the longest length.

Set the longestLength initially equal to zero. As the function iterates through the array, each word’s length is compared to the last recorded longest word, until the longest word is found.

In order to find the longest word, the .length property is used. A .length property returns the number of letters in a word. As the function iterates through each word, it counts the number of letters in each word, and this value is compared to the last longest word found. The iteration continues throughout the string. Once the iteration is completed, the longest found length is returned, as a numerical value.

Finished Code

And that’s it, relatively painless. As you can see the split() method is useful for splitting an array into individual words. And the .length property counts the number of characters are in each word. By enlisting the help of a for loop, the split() method and .length property allow us to find the length of the longest word in a string. Ta Da!