Is it possible to highlight text in html the same way that find does in the browser does i.e.
I would look into making all the highlighted bits <span>
s with a CSS class of âhighlightâ and doing the text coloring there.
Yes, we do as @rapropos has said. Here is our âhighlightifyâ pipe, in case it helps:
import {Pipe, PipeTransform} from '@angular/core';
import {isUndefined} from 'util';
@Pipe({name: 'highlightify'})
export class HighlightifyPipe implements PipeTransform {
transform(text: string, search): string {
try {
if (text && search && !isUndefined(text) && !isUndefined(search)) {
text = text.toString(); // sometimes comes in as number
search = search.trim();
if (search.length > 0) {
let pattern = search.trim().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
pattern = pattern.split(' ').filter((t) => {
return t.length > 0;
}).join('|');
let regex = new RegExp(pattern, 'gi');
text = text.replace(regex, (match) => `<span class="highlight">${match}</span>`);
}
}
}
catch (exception) {
console.error('error in highlight:', exception);
}
return text;
}
}
So, to use in a template, it would be something like: {{myText | highlightify:âwordâ}}.
Thanks @rapropos and @davidquinnjacobs Seems like a straight forward approach and will try it out in the next few days (unfortunately close family member taken into hospital so not much free time!).
@davidquinnjacobs
Finally got round to trying out the pipe and your example was a great help.
The only problem was that the example
{{myText | highlightify:âwordâ}}
was shown as a string, instead I used:
<span [outerHTML]=âmyText | highlightify:âaââ>
thanks dear its work perfect
i just add in my scss to change my requirment
.highlight {
background-color:#FFFF00;
}
Thanks @ davidquinnjacobs . It helped alot for my search bar. Instead of using span class=âhighlightâ , I used mark tag so that background color automatically gets applied instead of additional css.