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 {
215215 static Iterator <Match > matcher (RegExp regExp, String input) {
216216 return regExp.allMatches (input).iterator;
217217 }
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+ }
218232}
219233
220234class RegExpMatcherWrapper {
Original file line number Diff line number Diff line change @@ -347,6 +347,21 @@ export class RegExpWrapper {
347347 regExp . lastIndex = 0 ;
348348 return { re : regExp , input : input } ;
349349 }
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+ }
350365}
351366
352367export class RegExpMatcherWrapper {
Original file line number Diff line number Diff line change @@ -42,6 +42,12 @@ export function main() {
4242 // If not reset, the second attempt to test results in false
4343 expect ( RegExpWrapper . test ( re , str ) ) . toEqual ( true ) ;
4444 } ) ;
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+ } ) ;
4551 } ) ;
4652
4753 describe ( 'const' , ( ) => {
You can’t perform that action at this time.
0 commit comments