I need to highlight multiple words in a statement in HTML.
Ex: words: ['Hello', 'world', 'my']
Statement: 'Hello, welcome to my beautiful world'
I'm able to do it using regex find and replace in normal cases (like replacing the occurrence of each word by some markup like
<span class="highlight-span"> word </span>.
But the problem is if any words like spa, span, class, lass, high which are part of my replace markup string I will run into issues.)
Any ideas on doing this in a better way?
Below is the code for your reference.
import {
Pipe,
PipeTransform
} from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
transform(value: string, args: string): any {
if (args && value) {
let startIndex = value.toLowerCase().indexOf(args.toLowerCase());
if (startIndex != -1) {
let endLength = args.length;
let matchingString = value.substr(startIndex, endLength);
return value.replace(matchingString, "<span class="highlight-span">" + matchingString + "</span>");
}
}
return value;
}
}
In this case, I cannot have my search words like mar, mark. How can I get rid of such problems?