Back to Freecodecamp

Build a Longest Word Finder App

curriculum/challenges/english/blocks/lab-longest-word-in-a-string/a26cbbe9ad8655a977e1ceb5.md

latest2.4 KB
Original Source

--description--

In this lab, you will build a function that returns the length of the longest word in the provided sentence.

For example, in the sentence "The quick brown fox jumped over the lazy dog", the longest word is "jumped", which has a length of 6.

Objective: Fulfill the user stories below and get all the tests to pass to complete the lab.

User Stories:

  1. You should create a function named findLongestWordLength that takes a string as an argument.
  2. The function should return the length of the longest word in the string.

--hints--

You should create a function named findLongestWordLength.

js
assert.isFunction(findLongestWordLength);

findLongestWordLength should have a single parameter.

js
assert.lengthOf(findLongestWordLength, 1);

findLongestWordLength("The quick brown fox jumped over the lazy dog") should return a number.

js
assert.isNumber(
  findLongestWordLength('The quick brown fox jumped over the lazy dog')
);

findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.

js
assert.strictEqual(
  findLongestWordLength('The quick brown fox jumped over the lazy dog'),
  6
);

findLongestWordLength("May the force be with you") should return 5.

js
assert.strictEqual(findLongestWordLength('May the force be with you'), 5);

findLongestWordLength("Google do a barrel roll") should return 6.

js
assert.strictEqual(findLongestWordLength('Google do a barrel roll'), 6);

findLongestWordLength("Googling do a barrel roll") should return 8.

js
assert.strictEqual(findLongestWordLength('Googling do a barrel roll'), 8);

findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.

js
assert.strictEqual(
  findLongestWordLength(
    'What is the average airspeed velocity of an unladen swallow'
  ),
  8
);

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.

js
assert.strictEqual(
  findLongestWordLength(
    'What if we try a super-long word such as otorhinolaryngology'
  ),
  19
);

--seed--

--seed-contents--

js

--solutions--

js
function findLongestWordLength(str) {
  return str.split(' ').sort((a, b) => b.length - a.length)[0].length;
}

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