1 import { PipeTransform, Pipe } from '@angular/core'
2 import { SafeHtml } from '@angular/platform-browser'
4 // Thanks https://gist.github.com/adamrecsko/0f28f474eca63e0279455476cc11eca7#gistcomment-2917369
5 @Pipe({ name: 'highlight' })
6 export class HighlightPipe implements PipeTransform {
7 /* use this for single match search */
8 static SINGLE_MATCH = 'Single-Match'
9 /* use this for single match search with a restriction that target should start with search string */
10 static SINGLE_AND_STARTS_WITH_MATCH = 'Single-And-StartsWith-Match'
11 /* use this for global search */
12 static MULTI_MATCH = 'Multi-Match'
15 contentString: string = null,
16 stringToHighlight: string = null,
17 option = 'Single-And-StartsWith-Match',
18 caseSensitive = false,
19 highlightStyleName = 'search-highlight'
21 if (stringToHighlight && contentString && option) {
23 const caseFlag: string = !caseSensitive ? 'i' : ''
26 case 'Single-Match': {
27 regex = new RegExp(stringToHighlight, caseFlag)
30 case 'Single-And-StartsWith-Match': {
31 regex = new RegExp('^' + stringToHighlight, caseFlag)
35 regex = new RegExp(stringToHighlight, 'g' + caseFlag)
39 // default will be a global case-insensitive match
40 regex = new RegExp(stringToHighlight, 'gi')
44 const replaced = contentString.replace(
46 (match) => `<span class="${highlightStyleName}">${match}</span>`