File tree Expand file tree Collapse file tree
javascript/5_string-programs Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11// 1. Count Words of a String
22
3- // 1. Using split() Method
3+ // 1. Using split() Method
44
55{
66 const count = ( s ) => s . trim ( ) . split ( / \s + / ) . length ;
77
88 const s = "Hello, this is a simple test" ;
9- console . log ( count ( s ) ) ;
9+ console . log ( count ( s ) ) ;
10+ }
11+
12+ // 2. Using Regular Expressions
13+
14+ {
15+ const count = ( s ) => ( s . match ( / \b \w + \b / g) || [ ] ) . length ;
16+
17+ const s = "Hello, this is a simple test." ;
18+ console . log ( count ( s ) ) ;
19+ }
20+
21+ // 3. Using reduce() Method
22+
23+ {
24+ const count = ( s ) =>
25+ s
26+ . trim ( )
27+ . split ( / \s + / )
28+ . reduce ( ( count ) => count + 1 , 0 ) ;
29+ const s = "Hello, this is a simple test" ;
30+ console . log ( count ( s ) ) ;
31+ }
32+
33+ // 4. Using a Loop
34+
35+ {
36+ const count = ( s ) => {
37+ let c = 0 ;
38+ let inWord = false ;
39+ for ( const char of s ) {
40+ if ( / \s / . test ( char ) ) {
41+ inWord = false ;
42+ } else if ( ! inWord ) {
43+ inWord = true ;
44+ c ++ ;
45+ }
46+ }
47+ return c ;
48+ } ;
49+
50+ const s = "Hello, this is not a simple test" ;
51+ console . log ( count ( s ) ) ;
52+ }
53+
54+ // 5. Using matchAll() Method
55+
56+ {
57+ const count = ( s ) => [ ...s . matchAll ( / \b \w + \b / g) ] . length ;
58+ const s = "My name is amit" ;
59+ console . log ( count ( s ) ) ;
60+ }
61+
62+ // 6. Using Array.from() and filter() Methods
63+
64+ {
65+ const count = ( s ) => Array . from ( s . split ( / \s + / ) . filter ( Boolean ) ) . length ;
66+ const s = "Hello i am not amit" ;
67+ console . log ( count ( s ) ) ;
1068}
You can’t perform that action at this time.
0 commit comments