Skip to content

Instantly share code, notes, and snippets.

@mubasshir
Created April 4, 2018 10:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mubasshir/307184cc1aa63446cefd84b4455af3e7 to your computer and use it in GitHub Desktop.
Angular 2 Search Highlight Pipe. Make searched char bold
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
transform(text: string, search): string {
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) => `<span class="search-highlight">${match}</span>`);
} else {
return text;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment