This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function longestWord(str) { | |
// Match all the words and numbers | |
const wordsArray = str.toLowerCase().match(/[a-z0-9]+/g) | |
// Organise words (longest at the top) | |
const sortedList = wordsArray.sort((a,b) => { | |
return b.length - a.length | |
}) | |
// If you want to return the longest single word, this will suffice | |
// console.log(sortedList[0]) | |
// If multiple words match the same length, filter them out into an array | |
const longestWords = sortedList.filter((word) => { | |
return word.length == sortedList[0].length | |
}) | |
console.log(longestWords) | |
} | |
longestWord('Hello there young padawan!') | |
longestWord('Hello there!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment