File tree Expand file tree Collapse file tree 3 files changed +35
-0
lines changed Expand file tree Collapse file tree 3 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -215,6 +215,20 @@ class RegExpWrapper {
215
215
static Iterator <Match > matcher (RegExp regExp, String input) {
216
216
return regExp.allMatches (input).iterator;
217
217
}
218
+
219
+ static String replaceAll (RegExp regExp, String input, Function replace) {
220
+ final m = RegExpWrapper .matcher (regExp, input);
221
+ var res = "" ;
222
+ var prev = 0 ;
223
+ while (m.moveNext ()) {
224
+ var c = m.current;
225
+ res += input.substring (prev, c.start);
226
+ res += replace (c);
227
+ prev = c.start + c[0 ].length;
228
+ }
229
+ res += input.substring (prev);
230
+ return res;
231
+ }
218
232
}
219
233
220
234
class RegExpMatcherWrapper {
Original file line number Diff line number Diff line change @@ -347,6 +347,21 @@ export class RegExpWrapper {
347
347
regExp . lastIndex = 0 ;
348
348
return { re : regExp , input : input } ;
349
349
}
350
+ static replaceAll ( regExp : RegExp , input : string , replace : Function ) : string {
351
+ let c = regExp . exec ( input ) ;
352
+ let res = '' ;
353
+ regExp . lastIndex = 0 ;
354
+ let prev = 0 ;
355
+ while ( c ) {
356
+ res += input . substring ( prev , c . index ) ;
357
+ res += replace ( c ) ;
358
+ prev = c . index + c [ 0 ] . length ;
359
+ regExp . lastIndex = prev ;
360
+ c = regExp . exec ( input ) ;
361
+ }
362
+ res += input . substring ( prev ) ;
363
+ return res ;
364
+ }
350
365
}
351
366
352
367
export class RegExpMatcherWrapper {
Original file line number Diff line number Diff line change @@ -42,6 +42,12 @@ export function main() {
42
42
// If not reset, the second attempt to test results in false
43
43
expect ( RegExpWrapper . test ( re , str ) ) . toEqual ( true ) ;
44
44
} ) ;
45
+
46
+ it ( "should implement replace all" , ( ) => {
47
+ let re = / ( \d ) + / g;
48
+ let m = RegExpWrapper . replaceAll ( re , 'a1b2c' , ( match ) => `!${ match [ 1 ] } !` ) ;
49
+ expect ( m ) . toEqual ( 'a!1!b!2!c' ) ;
50
+ } ) ;
45
51
} ) ;
46
52
47
53
describe ( 'const' , ( ) => {
You can’t perform that action at this time.
0 commit comments