Skip to content

Instantly share code, notes, and snippets.

@ChrisBarberRiley
Last active November 1, 2020 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisBarberRiley/b8cfaf21a29922ff1764405054cb2e8f to your computer and use it in GitHub Desktop.
Save ChrisBarberRiley/b8cfaf21a29922ff1764405054cb2e8f to your computer and use it in GitHub Desktop.
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