简体   繁体   中英

How to make a Pipe with Regex in Angular2?

I'm trying to make a Pipe that would match the inputted text with Regex and then display the logic. If not found, it shouldn't do anything.

So, the Regex should match something like (m) or multiple: (n) (2) (abc) and then display the logic. Let's say that the "keywords" are:

(m) (n) (2) (abc) - only these, not the az or AZ

What I've made so far:

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

@Pipe({name:'regMatch'})
export class RegMatch implements PipeTransform {
    transform(value: string, arg?: any): any {
      //CODE HERE  
    }
}

How can I do this?

Thanks.

EDIT: if a matching is found an image should be displayed using Popover: https://github.com/pleerock/ng2-popover

If not, leave it as it is.

First I must say that I do not know anything about angular2-pipe specifically.

However if you are just looking for a JS way to loop through matches to process them you can use this regular expression: \\((.+?)\\) ( example ).

This can be utilized like below:

var targetText = "(word1) other words (word2)";
var reg = new RegExp(/\((.+?)\)/);   
var result;
while((result = reg.exec(targetText)) !== null) {
    var matchedContents = result[1]; //this will be the inside of each set of ()
    console.log(matchedContents);
    //Outputs:
    //word1
    //word2
    //DO Something...
}

Again I'm not sure about Pipes and how this can specifically be used for your case but I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM