Skip to content

Commit 0710098

Browse files
committed
Longest word JS es6 solution
1 parent f84a5f1 commit 0710098

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

longestWord.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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-z0-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"));

0 commit comments

Comments
 (0)