Longest Word JavaScript challenge

zamfir80

Razvan Zamfir

Posted on February 11, 2023

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

πŸ’– πŸ’ͺ πŸ™… 🚩
zamfir80
Razvan Zamfir

Posted on February 11, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related