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 1+ // 5. Check if a String Starts With Another String
2+
3+ // 1. Using String.startsWith() Method
4+
5+ {
6+ let s = "Hello WOrld" ;
7+ let pre = "Hello" ;
8+ if ( s . startsWith ( pre ) ) {
9+ console . log ( `The string starts with '${ pre } '` ) ;
10+ } else {
11+ console . log ( `The string does not starts with '${ pre } '` ) ;
12+ }
13+ }
14+
15+ // 2. Using String.slice() Method
16+
17+ {
18+ let s = "Hello world" ;
19+ let prefix = "Hello" ;
20+ if ( s . slice ( 0 , prefix . length ) === prefix ) {
21+ console . log ( `The string starts with '${ prefix } '` ) ;
22+ } else {
23+ console . log ( `The string does not start with '${ prefix } '` ) ;
24+ }
25+ }
26+
27+ // 3. Using String.indexOf() Method
28+
29+ {
30+ let s = "Hello World" ;
31+ let prefix = "Hello" ;
32+ if ( s . indexOf ( prefix ) === 0 ) {
33+ console . log ( `The string starts with "${ prefix } "` ) ;
34+ } else {
35+ console . log ( `The string does not start with '${ prefix } '` ) ;
36+ }
37+ }
38+
39+ // 4. Using String.substr() Method
40+
41+ {
42+ let s = "Hello World" ;
43+ let prefix = "Hello" ;
44+ if ( s . substr ( 0 , prefix . length ) === prefix ) {
45+ console . log ( `The string starts with "${ prefix } "` ) ;
46+ } else {
47+ console . log ( `The string does not start with '${ prefix } '` ) ;
48+ }
49+ }
You can’t perform that action at this time.
0 commit comments