DEV Community

Cover image for Longest Word JavaScript challenge
Razvan Zamfir
Razvan Zamfir

Posted on • Edited on

8

Longest Word JavaScript challenge

Coderbyte has this challenge among the free ones:

Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may also contain numbers, for example "Hello world123 567".

Here is my solution, with explanations in the form of comments:

function LongestWord(sen) { 
  // An aray of words made up of letters only
  let cleanWords = [];

  let words = sen.split(' ');
  words.forEach(word => {
    // Clean up the words and push them into "cleanWords"
    cleanWords.push(word.replace(/[^a-zA-Z0-9]/g, ''));
  });

  // Order by size
  let cleanWordsBySize = cleanWords.sort((a, b) => b.length - a.length);

  // Get the first
  return cleanWordsBySize[0];
}
Enter fullscreen mode Exit fullscreen mode

It passed all the tests. :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️