Back to Freecodecamp

Challenge 102: Longest Word

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c5.md

latest1.7 KB
Original Source

--description--

Given a sentence string, return the longest word in the sentence.

  • Words are separated by a single space.
  • Only letters (a-z, case-insensitive) count toward the word's length.
  • If there are multiple words with the same length, return the first one that appears.
  • Return the word as it appears in the given string, with punctuation removed.

--hints--

longestWord("The quick red fox") should return "quick".

js
assert.equal(longestWord("The quick red fox"), "quick");

longestWord("Hello coding challenge.") should return "challenge".

js
assert.equal(longestWord("Hello coding challenge."), "challenge");

longestWord("Do Try This At Home.") should return "This".

js
assert.equal(longestWord("Do Try This At Home."), "This");

longestWord("This sentence... has commas, ellipses, and an exclamation point!") should return "exclamation".

js
assert.equal(longestWord("This sentence... has commas, ellipses, and an exclamation point!"), "exclamation");

longestWord("A tie? No way!") should return "tie".

js
assert.equal(longestWord("A tie? No way!"), "tie");

longestWord("Wouldn't you like to know.") should return "Wouldnt".

js
assert.equal(longestWord("Wouldn't you like to know."), "Wouldnt");

--seed--

--seed-contents--

js
function longestWord(sentence) {

  return sentence;
}

--solutions--

js
function longestWord(sentence) {
  const words = sentence.split(" ");
  let longest = "";

  for (let word of words) {
    const cleaned = word.replace(/[^a-z]/gi, "");
    if (cleaned.length > longest.length) {
      longest = cleaned;
    }
  }

  return longest;
}