eric.dummy
eric.dummy

Reputation: 399

Making a Pipe with Regex on Angular2

I've already asked the similar question here: stackoverflow.com/questions/42674096/how-to-make-a-pipe-with-regex-in-angular2/

Now, I did try the following from the given answer:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name:'regMatch'})
export class RegMatch implements PipeTransform {
    transform(value: string, arg?: any): any {
        let targetMatched = $('div.poll').text();
       // console.log(targetMatched );
        let reg = new RegExp(/\((.+?)\)/);
        let result: any;
        do {
            let matched:any = result;
            console.log(matched);
        }
        while((result = reg.exec(target)) !== null)
    }
}

What happens is, when I put this pipe | regMatch the loop crashes the browser.

How can I solve this? How can I match the (a) (b) (c) or similar and then let's say BOLD the $('div.poll').text();

Upvotes: 1

Views: 5821

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

You are running a loop with a regex that does not contain a /g (global modifier). That means, that each time your regex finds a match, the lastIndex property will not change, and during the next iteration, the same match will be found, and so on and so forth, causing an infinite loop.

See String#exec documentation at MDN:

lastIndex     The index at which to start the next match. When "g" is absent, this will remain as 0.

Use

let reg = /\([^)]+\)/g;

It will match all occurrences of (, then 1+ chars other than ) and then a ).

Upvotes: 2

Related Questions