-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex16.js
48 lines (39 loc) · 1.02 KB
/
ex16.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function isUpperCase(code) {
return (code >= 65 && code <= 90)
}
function isLetter(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
}
function countWords(str = '', patternopt) {
let count = 0
if (patternopt) {
const regex = new RegExp(patternopt, 'g')
const substrings = str.match(regex) || []
return substrings.length
}
for (let i = 0; i < str.length; i++) {
if (
str[i] === ' ' &&
isLetter(str.charCodeAt(i - 1))
) {
count++
}
if (
isUpperCase(str.charCodeAt(i)) &&
str[i - 1] !== ' ' &&
str[i - 1] !== undefined
) {
count++
}
}
return count + 1
}
console.log(countWords('Tony Tony Ch0pper'))
// => 3
console.log(countWords('TonyTonyCh0pper'))
// => 3
console.log(countWords('Tony Tony - Ch0pper'))
// => 3
console.log(countWords('Coucou je suis là', 'ou'))
// => 3
console.log(countWords('Coucou je suis là', /To/))