-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountWords.js
More file actions
executable file
·69 lines (53 loc) · 1.21 KB
/
countWords.js
File metadata and controls
executable file
·69 lines (53 loc) · 1.21 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 1. Count Words of a String
// 1. Using split() Method
{
const count = (s) => s.trim().split(/\s+/).length;
const s = "Hello, this is a simple test";
console.log(count(s));
}
// 2. Using Regular Expressions
{
const count = (s) => (s.match(/\b\w+\b/g) || []).length;
const s = "Hello, this is a simple test.";
console.log(count(s));
}
// 3. Using reduce() Method
{
const count = (s) =>
s
.trim()
.split(/\s+/)
.reduce((count) => count + 1, 0);
const s = "Hello, this is a simple test";
console.log(count(s));
}
// 4. Using a Loop
{
const count = (s) => {
let c = 0;
let inWord = false;
for (const char of s) {
if (/\s/.test(char)) {
inWord = false;
} else if (!inWord) {
inWord = true;
c++;
}
}
return c;
};
const s = "Hello, this is not a simple test";
console.log(count(s));
}
// 5. Using matchAll() Method
{
const count = (s) => [...s.matchAll(/\b\w+\b/g)].length;
const s = "My name is amit";
console.log(count(s));
}
// 6. Using Array.from() and filter() Methods
{
const count = (s) => Array.from(s.split(/\s+/).filter(Boolean)).length;
const s = "Hello i am not amit";
console.log(count(s));
}