DEV Community

Cover image for Longest Word JavaScript challenge
Razvan Zamfir
Razvan Zamfir

Posted on • Updated on

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. :)

Top comments (0)