File tree 3 files changed +47
-19
lines changed
3 files changed +47
-19
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
1
+
2
+ // Demonstrates exec() in RegExp
3
+
4
+ var text = "This is a test of regular expressions." ;
5
+ var regex = / t e s t / ;
6
+
7
+ // The function exec() executes a search for a match in string. the result is an array.
8
+ var results = regex . exec ( text ) ;
9
+
10
+ console . log ( 'The match found in the text is: ' + results [ 0 ] ) ;
11
+ console . log ( 'And the index where it was found: ' + results . index ) ;
12
+ console . log ( 'And the input text in case you forgot: ' + results . input ) ;
13
+
14
+ // And again with capturing parentheses, the global flag, and a loop
15
+ text = "Now another test including phone numbers: 212-555-1234 and 917-555-4321 and 646.555.9876." ;
16
+ // Note the use of 'g' for global matches
17
+ regex = / ( \d + ) [ - . ] \d + [ - . ] \d + / g;
18
+
19
+ while ( ( results = regex . exec ( text ) ) != null ) {
20
+ console . log ( 'The full match found in the text is: ' + results [ 0 ] ) ;
21
+ console . log ( 'Group 1 of the match is: ' + results [ 1 ] ) ;
22
+ console . log ( 'And the index where it was found: ' + results . index ) ;
23
+ // console.log('And the input text in case you forgot: ' + results.input);
24
+ }
Original file line number Diff line number Diff line change
1
+
2
+ // Demonstrates match() in String
3
+
4
+ var text = "This is a test of regular expressions." ;
5
+ var regex = / t e s t / ;
6
+
7
+ // The function match() executes a search for a match in string.
8
+ // The result, just like with exec(), is an array.
9
+ var results = text . match ( regex ) ;
10
+
11
+ console . log ( 'The match found in the text is: ' + results [ 0 ] ) ;
12
+ console . log ( 'And the index where it was found: ' + results . index ) ;
13
+ console . log ( 'And the input text in case you forgot: ' + results . input ) ;
14
+
15
+ // Now capturing parentheses and the global flag match() works differently
16
+ // Note we can't actually get group 1 this way
17
+ text = "Now another test including phone numbers: 212-555-1234 and 917-555-4321 and 646.555.9876." ;
18
+ regex = / ( \d + ) [ - . ] \d + [ - . ] \d + / g;
19
+
20
+ results = text . match ( regex ) ;
21
+ for ( var i = 0 ; i < results . length ; i ++ ) {
22
+ console . log ( 'Match ' + i + ': ' + results [ i ] ) ;
23
+ }
You can’t perform that action at this time.
0 commit comments