All files / pipes/highlight highlight.pipe.ts

100% Statements 14/14
87.5% Branches 7/8
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291x 1x             1x   12x 12x   12x 4x     8x 8x 8x   8x       8x      
import { Pipe, PipeTransform } from '@angular/core';
import { escapeHtml } from '@drevo-web/shared';
 
@Pipe({
    name: 'highlight',
    standalone: true,
    pure: true,
})
export class HighlightPipe implements PipeTransform {
    transform(text: string | null | undefined, phrase: string | null | undefined): string {
        const raw = text ?? '';
        const term = (phrase ?? '').trim();
 
        if (!raw || !term) {
            return escapeHtml(raw);
        }
 
        const escapedText = escapeHtml(raw);
        const escapedTerm = escapeHtml(term);
        const regex = new RegExp(`(${this.escapeRegex(escapedTerm)})`, 'gi');
 
        return escapedText.replace(regex, '<mark class="highlighted-text">$1</mark>');
    }
 
    private escapeRegex(str: string): string {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
}