在Angular2上使用Regex制作管道 [英] Making a Pipe with Regex on Angular2

查看:159
本文介绍了在Angular2上使用Regex制作管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里问过类似的问题:stackoverflow.com/questions/42674096/how-to-make-a-pipe-with-regex-in-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)
    }
}

发生的事情是,当我将管道| regMatch放入时,循环使浏览器崩溃.

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

我该如何解决?如何匹配(a) (b) (c)或类似的内容,然后说BOLD $('div.poll').text();

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();

推荐答案

您正在使用不包含/g(全局修饰符)的正则表达式运行循环.这意味着,每次您的正则表达式找到匹配项时,lastIndex属性都不会更改,并且在下一次迭代期间,将找到相同的匹配项,依此类推,以此类推,从而导致无限循环.

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.

请参阅MDN上的 String#exec文档:

See String#exec documentation at MDN:

lastIndex   下一场比赛开始的索引.如果不存在"g",则该值将保持为0.

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

使用

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

它将匹配所有 个出现的(,然后匹配除)之外的1个以上字符,然后匹配一个).

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

这篇关于在Angular2上使用Regex制作管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆