A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h
I would suggest to escape the search String like this
RegExp.escape = function(string) {
if(string !== null){ return string.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
} else return null
};
@Pipe({
name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){ }
transform(value: any, args: any): any {
if (!args || value == null) {
return value;
}
// Match in a case insensitive maneer
const re = new RegExp(RegExp.escape(args), 'gi');
const match = value.match(re);
// If there's no match, just return the original value.
if (!match) {
return value;
}
const replacedValue = value.replace(re, "<mark>" + match[0] + "</mark>")
return this.sanitizer.bypassSecurityTrustHtml(replacedValue)
}
}