Longest Word JavaScript challenge
Razvan Zamfir
Posted on February 11, 2023
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];
}
It passed all the tests. :)
π πͺ π
π©
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.