Skip to content

Instantly share code, notes, and snippets.

@adamrecsko
Created May 1, 2016 20:28
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save adamrecsko/0f28f474eca63e0279455476cc11eca7 to your computer and use it in GitHub Desktop.
Save adamrecsko/0f28f474eca63e0279455476cc11eca7 to your computer and use it in GitHub Desktop.
Angular2 text highlight pipe
import {PipeTransform, Pipe} from 'angular2/core';
@Pipe({ name: 'highlight' })
export class HighLightPipe implements PipeTransform {
transform(text: string, [search]): string {
return search ? text.replace(new RegExp(search, 'i'), `<span class="highlight">${search}</span>`) : text;
}
}
/** Usage:
* <input type="text" [(ngModel)]="filter">
* <div [innerHTML]="myAwesomeText | highlight : filter"></div>
*
*/
@rafcontreras
Copy link

rafcontreras commented May 15, 2019

Usage:

<div [innerHTML]="
  string
    | highlightText
      : string
      : 'string'
      : boolean
      : 'string'
"></div>
<td>
  <div [innerHTML]="
    row.content
    | highlightText
      : searchInputValue
      : 'MULTI_MATCH'
      : true
      : 'your-class'
  "></div>
</td>

@Superkarl
Copy link

@rafcontreras use this, so you can search for special characters too:
stringToHighlight = stringToHighlight.replace(/([-[\]{}()*+?.\\^$|#,])/g,'\\$1');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment