eric.dummy
eric.dummy

Reputation: 399

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 a-z or A-Z

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.

Upvotes: 0

Views: 1451

Answers (1)

jjspace
jjspace

Reputation: 187

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.

Upvotes: 1

Related Questions