File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ // Description: For this challenge you will be determining the largest word in a string.
2+
3+ const LongestWord = ( sen ) => {
4+
5+ // we use the regex match function which searches the string for the
6+ // pattern and returns an array of strings it finds
7+ // in our case the pattern we define below returns words with
8+ // only the characters a through z and 0 through 9, stripping away punctuation
9+ // e.g. "hello$% ##all" becomes [hello, all]
10+ let arr = sen . match ( / [ a - z 0 - 9 ] + / gi) ;
11+
12+ // the array sort function takes a function as a parameter
13+ // which is used to compare each element in the array to the
14+ // next element in the array
15+ let sorted = arr . sort ( function ( a , b ) {
16+ return b . length - a . length ;
17+ } ) ;
18+
19+ // this array now contains all the words in the original
20+ // string but in order from longest to shortest length
21+ // so we simply return the first element
22+ return sorted [ 0 ] ;
23+
24+ }
25+
26+ console . log ( LongestWord ( "the ##quick brown fox jumped over the lazy dog" ) ) ;
You can’t perform that action at this time.
0 commit comments