Reputation: 154
Currently, I'm trying to implement highlighting on searched word in a text in my Angular project. I have the search operation as a separated component and I want to create a pipe that will highlight all the matches of the searched word in the text..
@Pipe({name: 'highlight'})
export class TextHighLightPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(text: any, search: string): SafeHtml {
//takes care of any special characters
if (search !== undefined && search !== null) {
search = search.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
text += '';
return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
'<span style="background-color: yellow">' + `${search}` + '</span>') : text);
}
}
This code works fine but it replaces all the matches with the searched word, so in case that I have a word that starts with upper case, when I search it with lower case, the transform function will replace it will the lower case one, which is the actual problem.. For example:
Text to search in: This is just an example text of this code
Search word: this
Result: this is just an example text of this code
Upvotes: 0
Views: 1355
Reputation: 154
I figured it out. So I only had to change this piece of code:
return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
'<span style="background-color: yellow">' + `${search}` + '</span>') : text);
}
To this:
return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(`(${search})`, 'gi'),
'<span style="background-color: yellow">' + `$1` + '</span>') : text);
Upvotes: 1