-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex9.js
34 lines (28 loc) · 975 Bytes
/
ex9.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* Have the function longestWord(sen) take the sen parameter being passed and
* return the largest word in the string. If there are two or more words that
* are the same length, return the first word from the string with that length.
* Ignore punctuation and assume sen will not be empty.
*/
function longestWord(sen) {
let validCharacters =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let maxLength = 0;
let longestWord = '';
for (let i = 0, length = 0, word = ''; i < sen.length; i++) {
let c = sen[i];
if (validCharacters.includes(c)) {
length++;
word += c;
} else {
length = 0;
word = '';
}
if (length > maxLength) {
maxLength = length;
longestWord = word;
}
}
return longestWord;
}
console.log(longestWord("Lorem ipsum dolor sit amet, consectetur"));