Highlighting text


#1

Is it possible to highlight text in html the same way that find does in the browser does i.e.

search


#2

I would look into making all the highlighted bits <span>s with a CSS class of “highlight” and doing the text coloring there.


#3

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’}}.


#4

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!).


#5

@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’”>