Find the Longest Word in a String in JavaScript

Sonya Moisset
iDevOI
Published in
2 min readFeb 12, 2017

This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

In this algorithm, we want to look at each individual word and count how many letters are in each. Then, compare the counts to determine which word has the most characters and return the length of the longest word.

The Algorithm Challenge Description

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

Your response should be a number.

Provided test cases

findLongestWord("The quick brown fox jumped over the lazy dog") should return a number.findLongestWord("The quick brown fox jumped over the lazy dog") should return 6.findLongestWord("May the force be with you") should return 5.findLongestWord("Google do a barrel roll") should return 6.findLongestWord("What is the average airspeed velocity of an unladen swallow") should return 8.findLongestWord("What if we try a super-long word such as otorhinolaryngology") should return 19.

Find the Longest Word With a FOR Loop

For this solution, you will use the String.prototype.split() method

  • The split() method splits a String object into an array of strings by separating the string into sub strings.

We will need to add an empty space between the parenthesis of the split() method,

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

which will output an array of separated words:

var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

If you don’t add the space in the parenthesis, you will have this output:

var strSplit = 
[“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”,
“ “, “d”, “o”, “g”];

Here’s my solution, with embedded comments to help you understand it:

And here it is without my comments:

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

--

--

Sonya Moisset
iDevOI

Senior Security 🥑 || GitHub 🌟 || ☁️ OpenUK Ambassador || 🎓 CAPSLOCK & CyberGirls Lead Mentor || 👩🏻‍💻 Epic Women in Cyber/Tech initiatives