freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-algorithm-scripting/find-the-longest-word-in-a-...

2.3 KiB

id title isRequired challengeType forumTopicId
a26cbbe9ad8655a977e1ceb5 Find the Longest Word in a String true 5 16015

Description

Return the length of the longest word in the provided sentence. Your response should be a number. Remember to use Read-Search-Ask if you get stuck. Write your own code.

Instructions

Tests

tests:
  - text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return a number.
    testString: assert(typeof findLongestWordLength("The quick brown fox jumped over the lazy dog") === "number");
  - text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return 6.
    testString: assert(findLongestWordLength("The quick brown fox jumped over the lazy dog") === 6);
  - text: <code>findLongestWordLength("May the force be with you")</code> should return 5.
    testString: assert(findLongestWordLength("May the force be with you") === 5);
  - text: <code>findLongestWordLength("Google do a barrel roll")</code> should return 6.
    testString: assert(findLongestWordLength("Google do a barrel roll") === 6);
  - text: <code>findLongestWordLength("What is the average airspeed velocity of an unladen swallow")</code> should return 8.
    testString: assert(findLongestWordLength("What is the average airspeed velocity of an unladen swallow") === 8);
  - text: <code>findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")</code> should return 19.
    testString: assert(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") === 19);

Challenge Seed

function findLongestWordLength(str) {
  return str.length;
}

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

Solution

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");