Skip to content

Commit 91999e0

Browse files
committed
feat(facade): add RegExpWrapper.replaceAll to replace all matches using the provided function
1 parent aa966f5 commit 91999e0

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

modules/angular2/src/facade/lang.dart

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff 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

220234
class RegExpMatcherWrapper {

modules/angular2/src/facade/lang.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff 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

352367
export class RegExpMatcherWrapper {

modules/angular2/test/facade/lang_spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff 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', () => {

0 commit comments

Comments
 (0)