Created
April 29, 2018 17:02
-
-
Save MorenoMdz/c7962f1e67e2e37df10e01d6709b99c1 to your computer and use it in GitHub Desktop.
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
/** | |
* Return the longest word in a sentence | |
* Loop through an array of the words split from the string and compare the lengths | |
* 1 - Strip away any punctuation | |
* 2 - Separe the sentence into a list of words to retrieve words and lengths | |
* 3 - Loop through the list and comparte the words lenghts | |
*/ | |
// Match only what contains a-z case unsensitive or numbers | |
function LongestWOrd(sen) { | |
let arr = sen.match(/[a-z0-9]+/gi); | |
// Sort compares a array element with the next element in the array | |
let sorted = arr.sort(function(a, b) { | |
return b.length - a.length; | |
}); | |
// returns the first element of the new array | |
// Sort returns the longest length element at first | |
return sorted[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment