I needed two times the same pipe to match and select words in a text .
I maybe put later in a npm package,but until then,here it is
import { PipeTransform,Pipe } from '@angular/core';
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
  transform(text: string,search): string {
     // window.alert(text );
     //console.log(search );
    if (search && text) {
      let pattern = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,'\\$&');
      pattern = pattern.split(' ').filter((t) => {
        return t.length > 0;
      }).join('|');
      const regex = new RegExp(pattern,'gi');
      return text.replace(regex,(match) => `<b><i><strong>${match}</strong></i></b>`);
    } else {
      return text;
    }
  }
}
You can use by performing 3 steps:
- Creating a highPipe.ts and copying the code above
 - In File : app.module.ts,at @NgModule,ad declarations  add  HighlightPipe ( also,
import {HighlightPipe} from ‘./highPipe’; )
 - 
<span [innerHTML]=”name | highlight: selectedText”></span>
 
Things to improve:
1. The regex should be a parameter ( with the default value seen below)
2. How to select the word should be a parameter also ( here is <b><i> )
Leave a Reply